<?php
/**
 * Created by liecol on 2015/4/21.
 */
class StatisTicsAction extends Action {


		// 商品分享统计
		public function getStatisTicsList($name=NULL,$startTime=NULL,$endTime=NULL,$start=0,$limit=10 ,$isExport = NULL){
			$retVal = Session::init();
			if (!$retVal) {
				Output::instance()->resultCode(code_access_denied);
				return;
			}
			$customerId = Session::$user['customerId'];
			Session::switchCustomer(0);
			$ProductModel = M("module_product");
			Session::switchCustomer($customerId);

			if ($name) {
				$condition['pro.name'] = array('like',"%{$name}%");
			}
			if ($startTime != '' && $endTime != '') {
				$swhere['mfrom.createTime'] = array(array('egt',$startTime),array('elt',$endTime));
				$vwhere['mvisit.createTime'] = array(array('egt',$startTime),array('elt',$endTime));
				$where['proo.createTime'] = array(array('egt',$startTime),array('elt',$endTime));
			} else if ($startTime != '') {
				$swhere["mfrom.createTime"] = array('egt', $startTime);
				$vwhere["mvisit.createTime"] = array('egt', $startTime);
				$where["proo.createTime"] = array('egt', $startTime);
			} else if ($endTime != '') {
				$swhere["mfrom.createTime"] = array('elt', $endTime);
				$vwhere["mvisit.createTime"] = array('elt', $endTime);
				$where["proo.createTime"] = array('elt', $endTime);
			}

			$arr=$ProductModel
				->alias("pro")
				->join("LEFT JOIN wx_mivendor ven on ven.id = pro.vId")
				->where($condition)
				->order("pro.createTime DESC")
				->limit("$start, $limit")
				->field('pro.id,pro.name, pro.picUrl,pro.fixedPrice,pro.createTime,ven.name as vname')
				->select();
			if ($isExport) {
				$arr=$ProductModel
				->alias("pro")
				->join("LEFT JOIN wx_mivendor ven on ven.id = pro.vId")
				->where($condition)
				->order("pro.createTime DESC")
				->field('pro.id,pro.name, pro.picUrl,pro.fixedPrice,pro.createTime,ven.name as vname')
				->select();
			}
				foreach ($arr as $key => $value) {
					$where['prod.pid'] = $value['id'];
					$where['proo.status'] = array("in",array('ok','delivering','delivered'));
					//$where['proo.status'] = 'ok';
					$arr[$key]['ordercount']=$ProductModel
						->alias("pro")
						->join("LEFT JOIN wx_module_product_order_detail prod on pro.id = prod.pid")
						->join("RIGHT JOIN wx_module_product_order proo on proo.id = prod.oid")
						->where($where)
						->count();
				}
				foreach ($arr as $k1 => $v1) {
					$swhere['msha.moduleId'] = $v1['id'];
					$swhere['msha.module'] = 'product';
					$arr[$k1]['shareCount']=$ProductModel
						->alias("pro")
						->join("LEFT JOIN wx_mishare msha on msha.moduleId = pro.id")
						->join("RIGHT JOIN wx_mishare_from mfrom on msha.id = mfrom.sId")
						->where($swhere)
						->count();
				}
				foreach ($arr as $k2 => $v2) {
					$vwhere['msha.moduleId'] = $v2['id'];
					$vwhere['msha.module'] = 'product';
					$arr[$k2]['viewCount']=$ProductModel
						->alias("pro")
						->join("LEFT JOIN wx_mishare msha on msha.moduleId = pro.id")
						->join("LEFT JOIN wx_mishare_visit mvisit on msha.id = mvisit.sId")
						->where($vwhere)
						->count();
				}
				foreach ($arr as $k3 => $v3) {
					$vwhere['msha.moduleId'] = $v3['id'];
					$vwhere['msha.module'] = 'product';
					$midata=$ProductModel
						->alias("pro")
						->join("LEFT JOIN wx_mishare msha on msha.moduleId = pro.id")
						->join("LEFT JOIN wx_mishare_visit mvisit on msha.id = mvisit.sId")
						->join("right JOIN wx_quan_user quser on quser.uid = mvisit.uId")
						->where($vwhere)
						->group("mvisit.id")
						->field("mvisit.id")
						->select();
					$arr[$k3]['MiviewCount'] = count($midata);
				}
			if ($isExport) {
					$expCellName  = array(
						array('name','商品名称'),
						array('fixedPrice','价格'),
						array('vname','供应商'),
						array('ordercount','成交单数'),
						array('viewCount','浏览次数'),
						array('MiviewCount','密友浏览'),
						array('shareCount','分享次数'),
					);
					Output::instance()->objArrayExcel('商品分享统计', $expCellName, $arr);
			}
			if ($arr) {
				$count=$ProductModel
				->alias("pro")
				->join("LEFT JOIN wx_mivendor ven on ven.id = pro.vId")
				->where($condition)
				->order("pro.createTime DESC")
				->field('pro.id,pro.name, pro.picUrl,pro.fixedPrice,pro.createTime,ven.name as vname')
				->count();
				Output::instance()->objArray($arr,$count);
			} else {
				Output::instance()->resultCode(code_success);
			}
		}


		public function getMiyouStatisTicsList($name=NULL,$phone=NULL,$startTime=NULL,$endTime=NULL,$start=0,$limit=10, $isExport = NULL,$quanName=''){
			$retVal = Session::init();
			if (!$retVal) {
				Output::instance()->resultCode(code_access_denied);
				return;
			}
			$customerId = Session::$user['customerId'];
			Session::switchCustomer(0);
			$QuanModel = M("quan_user");
			$productOrderModel = M("module_product_order");
			$MvisitModel = M("mishare_visit");
			Session::switchCustomer($customerId);
			if (!empty($name)) {
				$where['quser.nickName'] = array('like',"%{$name}%");
			}
			if (!empty($phone)) {
				$where['quser.phone'] = array('like',"%{$phone}%");
			}
			$where['myq.name']=array('like',"%{$quanName}%");
			if ($startTime != '' && $endTime != '') {
				$pwhere['pro.createTime'] = array(array('egt',$startTime),array('elt',$endTime));
				$owhere['pro.createTime'] = array(array('egt',$startTime),array('elt',$endTime));
				$vwhere['mvisit.createTime'] = array(array('egt',$startTime),array('elt',$endTime));
			} else if ($startTime != '') {
				$pwhere["pro.createTime"] = array('egt', $startTime);
				$owhere["pro.createTime"] = array('egt', $startTime);
				$vwhere["mvisit.createTime"] = array('egt', $startTime);
			} else if ($endTime != '') {
				$pwhere["pro.createTime"] = array('elt', $endTime);
				$owhere["pro.createTime"] = array('elt', $endTime);
				$vwhere["mvisit.createTime"] = array('elt', $endTime);
			}

			$where['identity'] = 1;
			$where['auser.isBind'] = 1;
			$arr = $QuanModel
				->alias("quser")
				->join("LEFT JOIN wx_".$customerId."_user as auser on auser.id=quser.uid")
				->join("LEFT JOIN wx_miyouquan as myq on myq.id=quser.qid")
				->where($where)
				->order("quser.createTime DESC")
				->limit("$start, $limit")
				->field("quser.id,quser.nickName,quser.headImgUrl,quser.uid,quser.qid,auser.phone,quser.createTime,GROUP_CONCAT(myq.name) as myqname")
				->group("quser.id")
				->select();
			if ($isExport) {
				$arr = $QuanModel
				->alias("quser")
				->join("LEFT JOIN wx_".$customerId."_user as auser on auser.id=quser.uid")
				->join("LEFT JOIN wx_miyouquan as myq on myq.id=quser.qid")
				->where($where)
				->order("quser.createTime DESC")
				->field("quser.id,quser.nickName,quser.headImgUrl,quser.uid,quser.qid,auser.phone,quser.createTime,GROUP_CONCAT(myq.name) as myqname")
				->group("quser.id")
				->select();
			}
			foreach ($arr as $key => $value) {
				$vwhere['mvisit.uid'] = $value['uid'];
				$arr[$key]['readcount']=$MvisitModel
				->alias("mvisit")
				->where($vwhere)
				->count();
			}
			foreach ($arr as $k1 => $v1) {
				$pwhere['pro.miUid'] = $v1['uid'];
				$pwhere['pro.qId']=$v1['qid'];
				//$pwhere['status'] = 'ok';
				$pwhere['status'] = array("in",array('ok','delivering','delivered'));
				$arr[$k1]['ordercount']=$productOrderModel->alias("pro")
				->where($pwhere)
				->count();
			}
			foreach ($arr as $k2 => $v2) {
				$owhere['pro.miUid'] = $v2['uid'];
				$owhere['pro.qId']=$v2['qid'];
				//$owhere['pro.status'] = 'ok';
				$owhere['pro.status'] = array("in",array('ok','delivering','delivered'));
				$arr[$k2]['orderprice']=$productOrderModel
				->alias("pro")
				->join("LEFT JOIN wx_module_product_order_detail as prod on prod.oid=pro.id")
				->where($owhere)
				->sum("prod.isMiUserCut");
				$arr[$k2]['orderAllprice']=$productOrderModel
					->alias("pro")
					->where($owhere)
					->sum("pro.price");
			}
			if ($isExport) {
				$expCellName  = array(
					array('nickName','名称'),
					array('phone','手机号'),
					array('myqname','密友圈'),
					array('createTime','注册时间'),
					array('readcount','浏览次数'),
					array('ordercount','成交单数'),
					array('orderAllprice','销售金额'),
					array('orderprice','成交金额'),
				);
				Output::instance()->objArrayExcel('密友分享统计', $expCellName, $arr);
			}
			if ($arr) {
				$count= $QuanModel
				->alias("quser")
					->join("inner join wx_miyouquan as myq on quser.qid=myq.id")
				->join("LEFT JOIN wx_".$customerId."_user as auser on auser.id=quser.uid")
				->where($where)
				->order("quser.createTime DESC")
				->field("quser.nickName,quser.headImgUrl,quser.uid,quser.qid,auser.phone,quser.createTime")
				->count();
				Output::instance()->objArray($arr,$count);
			} else {
				Output::instance()->resultCode(code_success);
			}
		}
		public function getteamStatisTicsList($nickName='',$parentName='',$start=0,$limit=10){
			$retVal = Session::init();
			if (!$retVal) {
				Output::instance()->resultCode(code_access_denied);
				return;
			}
			$customerId = Session::$user['customerId'];
			Session::switchCustomer(0);
			$quanTeam = M("quan_team");
			$orderModel = M("module_product_order");
			$quanUser = M("quan_user");
			Session::switchCustomer($customerId);
			isset($nickName)&&$nickName?$where["b.fullName"]=array('like',"%$nickName%"):"";
            $where["a.cid"]=array('eq',$customerId);
			$where["a.deleted"]=array('eq',0);
			$nowData = date("Y-m-1 0:0:0");
			$result = $quanTeam->alias("a")
				->join("inner join wx_".$customerId."_user b on a.teamLeader = b.id")
				->join("wx_quan_team_month_statistics c on a.id=c.teamId and c.createTime>='$nowData'")
				->field("a.*,b.fullName,c.sales,c.order,c.person as prePerson,c.totalPerson as preTotalPerson,c.avgSales,c.salesReward")
				->where($where)->limit($start,$limit)->select();
			foreach($result as $key=>$value){
				$orderInfo = $quanUser->alias("a")
					->join("wx_module_product_order b on a.qid = b.qId and a.uid = b.miUid")
					->where("a.teamId=".$value['id']." and a.status=1 and a.deleted=0 and b.status='ok' and b.completionTime>'$nowData'")
					->field("sum(b.price) as sales,count(b.id) as orders")
					->find();
				!$orderInfo['sales']?$orderInfo['sales']=0:$orderInfo['sales']=$orderInfo['sales'];
				$result[$key]['nowSales']=$orderInfo['sales'];
				$result[$key]['nowOrders']=$orderInfo['orders'];
				$result[$key]['nowAvgSales']=round($orderInfo['sales']/$value['totalPerson'],2);
				$result[$key]['preTotalPerson']=$value['preTotalPerson']+$value['prePerson'];
				$result[$key]['person']=$quanUser->where("teamId = ".$value['id']." and status=1 and deleted=0 and joinTeamTime>'$nowData'")->count();
			}
			if($result){
				$count =  $quanTeam->alias("a")
					->join("inner join wx_".$customerId."_user b on a.teamLeader = b.id")
					->where($where)->count();
				Output::instance()->objArray($result,$count);
			}else{
				Output::instance()->resultCode();
			}

		}
		public function getteamdealdetail($id,$nickName='',$start=0,$limit=10){
			$retVal = Session::init();
			if (!$retVal) {
				Output::instance()->resultCode(code_access_denied);
				return;
			}
			$customerId = Session::$user['customerId'];
			Session::switchCustomer(0);
			$quanuser = M("quan_user");
			Session::switchCustomer($customerId);
			$where["a.deleted"]=array("eq",0);
			$where["a.status"]=array("eq",1);
			$where["a.teamId"]=array("eq",$id);
			$nowData = date("Y-m-1 0:0:0");
			isset($nickName)&&$nickName?$where["a.nickName"]=array("like","%$nickName%"):"";
			$result = $quanuser->alias("a")
				->join("wx_quan_user_month_statistics b on a.qid=b.quanId and a.uid = b.uid and b.createTime>='$nowData'")
				->where($where)
				->field("a.*,b.sales,b.order")
				->group("a.id")
				->limit($start,$limit)
				->order("sales desc")
				->select();
			if($result){
				$count = $quanuser->alias("a")
					->where($where)
					->count();
				Output::instance()->objArray($result,$count);
			}else{
				Output::instance()->resultCode();
			}
		}
		//删除团员
		public function delTeamUser($id){
			$retVal = Session::init();
			if (!$retVal) {
				Output::instance()->resultCode(code_access_denied);
				return;
			}
			$customerId = Session::$user['customerId'];
			Session::switchCustomer(0);
			$quanUser = M("quan_user");
			Session::switchCustomer($customerId);
			$teamInfo = $quanUser->alias("a")
				->join("inner join wx_quan_team b on a.teamId=b.id")
				->field("a.uid,b.teamLeader")
				->where("a.id=$id")
				->find();
			if($teamInfo['uid']==$teamInfo['teamLeader']){
				Output::instance()->resultCode(1,'团长不能删除！');
				return;
			}
			$param = new stdClass();
			$param->id=$id;
			Module::callModule("community",null,'deletedTeamUser',$param);
		}
		public function getmydealdetail($uid, $qid, $vname=NULL, $qname=NULL, $pname=NULL, $startTime=NULL,$endTime=NULL, $start = 0, $limit = 10, $isExport = NULL){
			$retVal = Session::init();
			if (!$retVal) {
				Output::instance()->resultCode(code_access_denied);
				return;
			}
			$customerId = Session::$user['customerId'];
			Session::switchCustomer(0);
			$MiafriendModel = M("miaccount_friend");
			Session::switchCustomer($customerId);

			if (!empty($vname)) {
				$where['miv.name'] = array('like',"%{$vname}%");
			}
			if (!empty($qname)) {
				$where['quan.name'] = array('like',"%{$qname}%");
			}
			if (!empty($pname)) {
				$where['pro.name'] = array('like',"%{$pname}%");
			}
			if ($startTime != '' && $endTime != '') {
				$where['fri.createTime'] = array(array('egt',$startTime),array('elt',$endTime));
			} else if ($startTime != '') {
				$where["fri.createTime"] = array('egt', $startTime);
			} else if ($endTime != '') {
				$where["fri.createTime"] = array('elt', $endTime);
			}

			$where['fri.quanId'] = $qid;
			$where['fri.uId'] = $uid;
			$where['fri.deleted'] = 0;
			$where['fri.type'] = 0;
			if ($isExport) {
				$arr = $MiafriendModel
				->alias("fri")
				->join("LEFT JOIN wx_miyouquan as quan on quan.id=fri.quanId")
				->join("LEFT JOIN wx_mivendor as miv on miv.id=fri.vId")
				->join("LEFT JOIN wx_module_product as pro on pro.id=fri.moduleId")
				->where($where)
				->order("fri.createTime DESC")
				->field("fri.description,fri.module,fri.moduleId,pro.name as pname,quan.name,quan.coins,miv.name as vname,fri.money,fri.createTime")
				->select();
					$expCellName  = array(
						array('description','商品名称'),
						array('name','密友圈'),
						array('vname','供应商'),
						array('createTime','成交时间'),
						array('money','成交金额'),
					);
					Output::instance()->objArrayExcel('密友分成详情信息', $expCellName, $arr);
			}else{
				$arr = $MiafriendModel
				->alias("fri")
				->join("LEFT JOIN wx_miyouquan as quan on quan.id=fri.quanId")
				->join("LEFT JOIN wx_mivendor as miv on miv.id=fri.vId")
				->join("LEFT JOIN wx_module_product as pro on pro.id=fri.moduleId")
				->where($where)
				->order("fri.createTime DESC")
				->limit("$start, $limit")
				->field("fri.description,fri.module,fri.moduleId,pro.name as pname,quan.name,quan.coins,miv.name as vname,fri.money,fri.createTime")
				->select();
			}
			if ($arr) {
				$count = $MiafriendModel->alias("fri")
				->join("LEFT JOIN wx_miyouquan as quan on quan.id=fri.quanId")
				->join("LEFT JOIN wx_mivendor as miv on miv.id=fri.vId")
				->join("LEFT JOIN wx_module_product as pro on pro.id=fri.moduleId")
				->where($where)
				->order("fri.createTime DESC")
				->field("fri.description,fri.module,fri.moduleId,pro.name as pname,quan.name,quan.coins,miv.name as vname,fri.money,fri.createTime")
				->count();
				Output::instance()->objArray($arr,$count);
			} else {
				Output::instance()->resultCode(code_success);
			}

		}
		//团队历史统计
		public function getTeamHistory($id){
			$retVal = Session::init();
			if (!$retVal) {
				Output::instance()->resultCode(code_access_denied);
				return;
			}
			$customerId = Session::$user['customerId'];
			Session::switchCustomer(0);
			$teamMonth = M("quan_team_month_statistics");
			Session::switchCustomer($customerId);
			$arr = $teamMonth->where("teamId=$id")->order("createTime desc")->select();
			if($arr){
				$count = $teamMonth->where("teamId=$id")->count();
				Output::instance()->objArray($arr,$count);
			}else{
				Output::instance()->resultCode();
			}
		}
		//密友历史统计
		public function getUserHistory($quanId,$uId){
			$retVal = Session::init();
			if (!$retVal) {
				Output::instance()->resultCode(code_access_denied);
				return;
			}
			$customerId = Session::$user['customerId'];
			Session::switchCustomer(0);
			$teamMonth = M("quan_user_month_statistics");
			Session::switchCustomer($customerId);
			$arr = $teamMonth->where("quanId=$quanId and uId=$uId")->order("createTime desc")->select();
			if($arr){
				$count = $teamMonth->where("quanId=$quanId and uId=$uId")->count();
				Output::instance()->objArray($arr,$count);
			}else{
				Output::instance()->resultCode();
			}
		}
		public function getmyqStatisTicsList($name=NULL, $nickName=NULL, $startTime=NULL,$endTime=NULL, $start = 0 ,$limit =10 ,$isExport = NULL){
			$retVal = Session::init();
			if (!$retVal) {
				Output::instance()->resultCode(code_access_denied);
				return;
			}
			$customerId = Session::$user['customerId'];
			Session::switchCustomer(0);
			$MiyqModel = M("miyouquan");
			Session::switchCustomer($customerId);
			// $mywhere['quser.deleted'] = 0;
			$mywhere['quser.identity'] = 0;
			/*$arr = $MiyqModel
				->alias("quan")
				->join("LEFT JOIN wx_quan_user as quser on quan.id=quser.qid")
				->join("LEFT JOIN wx_mishare_from as mfrom on mfrom.quanId=quan.id")
				//->join("LEFT JOIN SELECT count(mivi.miUid) as visitcount from wx_mishare_visit as mivi on mivi.miUid=quser.uid group by mivi.miUid")
				->field('count(mfrom.quanId) as sharecount,quan.id,quan.logo,quan.name,quan.miMaxCount,quan.coins,quan.lordAward,quan.createTime,quser.nickName')
				->where($where)
				->order("quan.createTime DESC")
				->group("quan.id")
				->limit("$start, $limit")
				->select();*/
			$where  = '';
			$pwhere = '';
			$qwhere = '';
			$uwhere = '';
			if (!empty($name)) {
				$pwhere .= "(quan.name LIKE '%$name%') ";
			}
			if(!empty($nickName)){
				$qwhere .= " (quser.nickName LIKE '%$nickName%')";
			}
			if ($startTime != '' && $endTime != '') {
				$where .= "(createTime >= '$startTime') AND (createTime <= '$endTime')";
				$uwhere .= "(qu.createTime >= '$startTime') AND (qu.createTime <= '$endTime')";
			} else if ($startTime != '') {
				$where .= "(createTime >= '$startTime')";
				$uwhere .= "(qu.createTime >= '$startTime')";
			} else if ($endTime != '') {
				$where .= "(createTime <= '$endTime')";
				$uwhere .= "(qu.createTime <= '$endTime')";
			}
			$sql = "SELECT *,quser.nickName,quan.createTime as myqcreateTime  FROM
					  (SELECT 
					      quan.id,quan.logo,quan.name,quan.miMaxCount,quan.coins,quan.lordAward,quan.createTime
					    FROM wx_miyouquan quan ";
				if ($pwhere !== '') {
					$sql .="where ".$pwhere;
				}
				$sql .="GROUP BY quan.id
					  ) as quan
					  LEFT JOIN wx_quan_user as quser 
					    on quan.id=quser.qid and ( quser.deleted = 0 ) AND ( quser.identity = 0 )LEFT JOIN (select 
					       count(quanId) as sharecount ,quanId from wx_mishare_from ";
				if ($where !== '') {
					$sql .= "where".$where;
				}
				$sql.=" group by quanId
					    ) as mfrom 
					      on mfrom.quanId=quan.id
					  LEFT JOIN 
					    (select 
					       count(qid) as myqusercount ,qid from wx_quan_user as qu left join wx_".$customerId."_user au on qu.uid = au.id";
				if ($where !== '') {
					$sql .= "and".$uwhere;
				}
				$sql.="group by qid
					    ) as muser 
					      on muser.qid=quan.id ";
				if ($qwhere !== '') {
					$sql .="where ".$qwhere;
				}
					$sql.= "ORDER BY quan.createTime DESC ";

				if (!$isExport) {
						$sql.=  "LIMIT ".$start."," . $limit;
				}
			$arr = $MiyqModel->query($sql);
			foreach ($arr as $key => $value) {
				$mqwhere['quan.id'] = $value['qid'];
				//$mqwhere['pro.status'] = 'ok';
				$mqwhere['pro.status'] = array("in",array('ok','delivering','delivered'));
				$data[$key]=$MiyqModel
				->alias("quan")
				->join("LEFT JOIN wx_module_product_order as pro on pro.qid=quan.id")
				->join("LEFT JOIN wx_module_product_order_detail as prod on prod.oid=pro.id")
				->where($mqwhere)
				->field("count(pro.qid) as ordercount, sum(pro.price) as orderprice")
				->select();
				$arr[$key]['ordercount'] = $data[$key][0]['ordercount'];
				$arr[$key]['orderprice'] = $data[$key][0]['orderprice'];
			}
			foreach ($arr as $k1 => $v1) {
				$viwhere['quan.id'] = $v1['qid'];
				$arr[$k1]['visitcount']=$MiyqModel
				->alias("quan")
				->join("right JOIN wx_quan_user as quser on quser.qid=quan.id")
				->join("right JOIN wx_mishare_visit as mivi on mivi.miUid=quser.uid")
				->where($viwhere)
				->count();
			}
			if ($isExport) {
					$expCellName  = array(
						array('nickName','主公'),
						array('miMaxCount','密友上限'),
						array('myqusercount','密友人数'),
						array('sharecount','分享次数'),
						array('visitcount','浏览次数'),
						array('ordercount','成交单数'),
						array('orderprice','成交金额'),
						array('lordAward','主公分成比例'),
						array('coins','主公收入'),
						array('createTime','创建时间'),
					);
					Output::instance()->objArrayExcel('密友圈分享统计', $expCellName, $arr);
			}
			if ($arr) {
				$count = $MiyqModel
				->alias("quan")
				->join("LEFT JOIN wx_quan_user as quser on quan.id=quser.qid")
				->field('quan.id,quan.logo,quan.name,quan.miMaxCount,quan.coins,quan.lordAward,quan.createTime,quser.nickName')
				->where($mywhere)
				->order("quan.createTime DESC")
				->count();
				Output::instance()->objArray($arr,$count);
			} else {
				Output::instance()->resultCode(code_success);
			}

		}

		public function getmyqdealdetail($qid, $vname=NUlL, $nickName=NULl, $pname=NUlL, $startTime=NULL,$endTime=NULL, $start = 0, $limit = 10, $isExport = NULL){
			$retVal = Session::init();
			if (!$retVal) {
				Output::instance()->resultCode(code_access_denied);
				return;
			}
			$customerId = Session::$user['customerId'];
			Session::switchCustomer(0);
			$MialoadModel = M("miaccount_lord");
			Session::switchCustomer($customerId);
			$where['loa.module'] = 'product';

			if (!empty($vname)) {
				$where['miv.name'] = array('like',"%{$vname}%");
			}
			if (!empty($nickName)) {
				$where['quser.nickName'] = array('like',"%{$nickName}%");
			}
			if (!empty($pname)) {
				$where['loa.description'] = array('like',"%{$pname}%");
			}

			if ($startTime != '' && $endTime != '') {
				$where['loa.createTime'] = array(array('egt',$startTime),array('elt',$endTime));
			} else if ($startTime != '') {
				$where["loa.createTime"] = array('egt', $startTime);
			} else if ($endTime != '') {
				$where["loa.createTime"] = array('elt', $endTime);
			}
			$where['loa.quanId'] = $qid;
			$where['loa.deleted'] = 0;
			$where['loa.type'] = 0;
			if ($isExport) {
				$arr = $MialoadModel
				->alias("loa")
				->join("LEFT JOIN wx_miyouquan as quan on quan.id=loa.quanId")
				->join("LEFT JOIN wx_mivendor as miv on miv.id=loa.vId")
				->join("LEFT JOIN wx_quan_user as quser on quser.uid=loa.uId")
				->join("LEFT JOIN wx_module_product as pro on pro.id=loa.moduleId")
				->join("LEFT JOIN wx_module_product_order_detail as prod on prod.pid=pro.id")
				->join("LEFT JOIN wx_module_product_order as proo on prod.oid=proo.id")
				->where($where)
				->order("loa.createTime DESC")
				->group("loa.id")
				->field("loa.description,loa.module,loa.moduleId,pro.name as pname,proo.price,miv.name as vname,quan.coins,quser.nickName,loa.money,loa.createTime")
				->select();
					$expCellName  = array(
						array('description','商品名称'),
						array('nickName','分享者'),
						array('vname','供应商'),
						array('createTime','成交时间'),
						array('money','主公分成'),
						array('price','成交金额'),

					);
					Output::instance()->objArrayExcel('密友圈主公分成详情', $expCellName, $arr);
			}else{
				$arr = $MialoadModel
				->alias("loa")
				->join("LEFT JOIN wx_miyouquan as quan on quan.id=loa.quanId")
				->join("LEFT JOIN wx_mivendor as miv on miv.id=loa.vId")
				->join("LEFT JOIN wx_quan_user as quser on quser.uid=loa.uId")
				->join("LEFT JOIN wx_module_product as pro on pro.id=loa.moduleId")
				->join("LEFT JOIN wx_module_product_order_detail as prod on prod.pid=pro.id")
				->join("LEFT JOIN wx_module_product_order as proo on prod.oid=proo.id")
				->where($where)
				->order("loa.createTime DESC")
				->limit("$start, $limit")
				->group("loa.id")
				->field("loa.description,loa.module,loa.moduleId,pro.name as pname,proo.price,miv.name as vname,quan.coins,quser.nickName,loa.money,loa.createTime")
				->select();
			}
			if ($arr) {
				$count = $MialoadModel
				->alias("loa")
				->join("LEFT JOIN wx_miyouquan as quan on quan.id=loa.quanId")
				->join("LEFT JOIN wx_mivendor as miv on miv.id=loa.vId")
				->join("LEFT JOIN wx_quan_user as quser on quser.uid=loa.uId")
				->join("LEFT JOIN wx_module_product as pro on pro.id=loa.moduleId")
				->where($where)
				->order("loa.createTime DESC")
				->group("loa.id")
				->field("loa.description,loa.module,loa.moduleId,pro.name as pname,miv.name as vname,quan.coins,quser.nickName,loa.money,loa.createTime")
				->select();
				$count = count($count);
				Output::instance()->objArray($arr,$count);
			} else {
				Output::instance()->resultCode(code_success);
			}

		}
		//素材统计
		public function getscStatisTicsList($title=NULL, $startTime=NULL,$endTime=NULL, $start = 0 ,$limit =10 ,$isExport = NULL){
			$retVal = Session::init();
			if (!$retVal) {
				Output::instance()->resultCode(code_access_denied);
				return;
			}
			$customerId = Session::$user['customerId'];
			Session::switchCustomer(0);
			$MialoadModel = M("micontent");
			Session::switchCustomer($customerId);
			$swhere = '';
			$qwhere = '';
			$vwhere = '';
			$vvwhere = '';
			$owhere = '';
			if(!empty($title)){
				$qwhere .= " (content.title LIKE '%$title%')";
			}
			if ($startTime != '' && $endTime != '') {
				$swhere .= "(sharef.createTime >= '$startTime') AND (sharef.createTime <= '$endTime')";
				$vwhere .= "(visit.createTime >= '$startTime') AND (visit.createTime <= '$endTime')";
				$vvwhere .= "(visit1.createTime >= '$startTime') AND (visit1.createTime <= '$endTime')";
				$owhere .= "(prod.createTime >= '$startTime') AND (prod.createTime <= '$endTime')";
			} else if ($startTime != '') {
				$swhere .= "(sharef.createTime >= '$startTime')";
				$vwhere .= "(visit.createTime >= '$startTime')";
				$vvwhere .= "(visit1.createTime >= '$startTime')";
				$owhere .= "(prod.createTime >= '$startTime')";
			} else if ($endTime != '') {
				$swhere .= "(sharef.createTime <= '$endTime')";
				$vwhere .= "(visit.createTime <= '$endTime')";
				$vvwhere .= "(visit1.createTime <= '$endTime')";
				$owhere .= "(prod.createTime <= '$endTime')";
			}
			$sql = "SELECT * FROM
					  (SELECT 
					      content.id,content.title,content.createTime FROM wx_micontent content where deleted = 0 ";
				if ($qwhere !== '') {
					$sql .="and ".$qwhere;
				}
				$sql.= " GROUP BY content.id
					  ) as content
						LEFT JOIN 
					    (select 
					       count(sharef.id) as sharecount ,sha.moduleId,sha.module from wx_mishare as sha left join wx_mishare_from sharef on sha.id = sharef.sId where sha.module = 'micontent' ";
				if ($swhere !== '') {
					$sql .="and ".$swhere;
				}
				$sql.= " group by sha.id
					    ) as shar 
					      on content.id=shar.moduleId
					    LEFT JOIN 
					    (select 
					       count(visit.id) as visitcount ,sha.moduleId,sha.module from wx_mishare as sha left join wx_mishare_visit visit on sha.id = visit.sId where sha.module = 'micontent' ";
				if ($vwhere !== '') {
					$sql .="and ".$vwhere;
				}
				$sql.= " group by sha.id
					    ) as visit 
					      on content.id=visit.moduleId
					    LEFT JOIN 
					    (select 
					       count(visit1.id) as procount ,sha.moduleId,sha.module,visit.guid,visit.fromPage,visit1.fromGuid from wx_mishare as sha left join wx_mishare_visit visit on sha.id = visit.sId join wx_mishare_visit visit1 on visit.guid = visit1.fromGuid where sha.module = 'micontent' and visit1.fromPage = 'product_detail' ";
				if ($vvwhere !== '') {
					$sql .="and ".$vvwhere;
				}
				$sql.= " group by sha.id
					    ) as pvisit 
					      on content.id=pvisit.moduleId
					    LEFT JOIN 
					    (select 
					       count(visit1.id) as dpcount ,sha.moduleId,sha.module,visit.guid,visit.fromPage,visit1.fromGuid from wx_mishare as sha left join wx_mishare_visit visit on sha.id = visit.sId left join wx_mishare_visit visit1 on visit.guid = visit1.fromGuid where sha.module = 'micontent' and visit1.fromPage = 'shopIndex' ";
				if ($vvwhere !== '') {
					$sql .="and ".$vvwhere;
				}
				$sql.= " group by sha.id
					    ) as dvisit 
					      on content.id=dvisit.moduleId
					    LEFT JOIN 
					    (select 
					       count(prod.id) as ordercount ,sum(prodel.price) as orderprice, sha.moduleId,sha.module,prod.status,prodel.sId from wx_mishare as sha left join wx_module_product_order_detail prodel on sha.id = prodel.sId left join wx_module_product_order prod on prod.id = prodel.oid where sha.module = 'micontent' and prod.status = 'ok' ";
				if ($owhere !== '') {
					$sql .="and ".$owhere;
				}
				$sql.= " group by sha.id
					    ) as oidcount 
					      on content.id=dvisit.moduleId
						ORDER BY content.createTime DESC ";
				if (!$isExport) {
						$sql.=  "LIMIT ".$start."," . $limit;
				}
				$arr = $MialoadModel->query($sql);

				if ($isExport) {
					$expCellName  = array(
						array('title','名称'),
						array('createTime','创建时间'),
						array('sharecount','分享次数'),
						array('visitcount','浏览次数'),
						array('procount','进入商品次数'),
						array('dpcount','进入店铺次数'),
						array('ordercount','成交单数'),
						array('orderprice','成交金额'),
					);
					Output::instance()->objArrayExcel('素材分享统计', $expCellName, $arr);
				}
			if ($arr) {
				$where['deleted'] = 0;
				$count = $MialoadModel
				->where($where)
				->count();
				Output::instance()->objArray($arr,$count);
			} else {
				Output::instance()->resultCode(code_success);
			}
		}

		// 更改素材函数(待测试，另分享次数查询方式有待验证,建议更改visit查询方式，或者更换进入商品次数和进入店铺次数的统计方式)
		public function getscStatisTicsList2($title=NULL, $startTime=NULL,$endTime=NULL, $start = 0 ,$limit =10 ,$isExport = NULL){
			$retVal = Session::init();
			if (!$retVal) {
				Output::instance()->resultCode(code_access_denied);
				return;
			}
			$customerId = Session::$user['customerId'];
			Session::switchCustomer(0);
			$MialoadModel = M("micontent");
			$MishareModel = M("mishare");
			Session::switchCustomer($customerId);

			if (!empty($title)) {
				$cwhere['content.title'] = array('like',"%{$title}%");
			}

			if ($startTime != '' && $endTime != '') {
				$sharew['sharef.createTime'] = array(array('egt',$startTime),array('elt',$endTime));
				$visitw['visit.createTime'] = array(array('egt',$startTime),array('elt',$endTime));
				$prow['visit1.createTime'] = array(array('egt',$startTime),array('elt',$endTime));
				$dpw['visit1.createTime'] = array(array('egt',$startTime),array('elt',$endTime));
				$orderw['prod.createTime'] = array(array('egt',$startTime),array('elt',$endTime));
			} else if ($startTime != '') {
				$sharew["sharef.createTime"] = array('egt', $startTime);
				$visitw["visit.createTime"] = array('egt', $startTime);
				$prow["visit1.createTime"] = array('egt', $startTime);
				$dpw["visit1.createTime"] = array('egt', $startTime);
				$orderw["prod.createTime"] = array('egt', $startTime);
			} else if ($endTime != '') {
				$sharew["sharef.createTime"] = array('elt', $endTime);
				$visitw["visit.createTime"] = array('elt', $endTime);
				$prow["visit1.createTime"] = array('elt', $endTime);
				$dpw["visit1.createTime"] = array('elt', $endTime);
				$orderw["prod.createTime"] = array('elt', $endTime);
			}

			$cwhere['content.deleted'] = 0;
			if (!$isExport) {
				$arr = $MialoadModel->alias("content")
					->where($cwhere)
					->limit($start,$limit)
					->order("content.createTime desc")
					->field("content.id,content.title,content.createTime")
					->select();
			}else{
				$arr = $MialoadModel->alias("content")
					->where($cwhere)
					->order("content.createTime desc")
					->field("content.id,content.title,content.createTime")
					->select();
			}
			foreach ($arr as $key => $value) {
				$sharew['sha.module'] = 'micontent';
				$sharew['sha.moduleId'] = $value['id'];
				$sharearr = $MishareModel->alias("sha")
					->join("LEFT JOIN wx_mishare_stat as sharef on sha.id = sharef.sId ")
					->where($sharew)
					->group("sha.id")
					->field("sum(sharef.shareCount) as sharecount,sum(sharef.pv) as visitcount")
					->select();

				if ($sharearr[0]) {
					$arr[$key]['sharecount'] = $sharearr[0]['sharecount'];
					$arr[$key]['visitcount'] = $sharearr[0]['visitcount'];
				}
			}
			/**foreach ($arr as $key => $value) {
				$prow['sha.module'] = 'micontent';
				$prow['sha.moduleId'] = $value['id'];
				$prow['visit1.fromPage'] = 'product_detail';
				$arr[$key]['procount'] = $MishareModel->alias("sha")
					->join("LEFT JOIN wx_mishare_visit as visit on sha.id = visit.sId ")
					->join("LEFT JOIN wx_mishare_visit as visit1 on visit.guid = visit1.fromGuid ")
					->where($prow)
					->group("sha.id")
					->count("visit1.id");
			}
			foreach ($arr as $key => $value) {
				$dpw['sha.module'] = 'micontent';
				$dpw['sha.moduleId'] = $value['id'];
				$dpw['visit1.fromPage'] = 'shopIndex';
				$arr[$key]['dpcount'] = $MishareModel->alias("sha")
					->join("LEFT JOIN wx_mishare_visit as visit on sha.id = visit.sId ")
					->join("LEFT JOIN wx_mishare_visit as visit1 on visit.guid = visit1.fromGuid ")
					->where($dpw)
					->group("sha.id")
					->count("visit1.id");
			}
		**/
			foreach ($arr as $key => $value) {
				$conid = $value['id'];
				$orderw['sha.module'] = 'micontent';
				$orderw['sha.moduleId'] = $value['id'];
				$orderw['prod.status'] = 'ok';

				$orderarr = $MishareModel->alias("sha")
					->join("LEFT JOIN wx_module_product_order_detail as prodel on sha.id = prodel.sId ")
					->join("LEFT JOIN wx_module_product_order as prod on  prod.id = prodel.oid ")
					->where($orderw)
					->group("sha.id")
					->field("count(prod.id) as ordercount,sum(prodel.price) as orderprice")
					->select();
				if ($orderarr[0]) {
					$arr[$key]['ordercount'] = $orderarr[0]['ordercount'];
					$arr[$key]['orderprice'] = $orderarr[0]['orderprice'];
				}
			}
				if ($isExport) {
					$expCellName  = array(
						array('title','名称'),
						array('createTime','创建时间'),
						array('sharecount','分享次数'),
						array('visitcount','浏览次数'),
						array('procount','进入商品次数'),
						array('dpcount','进入店铺次数'),
						array('ordercount','成交单数'),
						array('orderprice','成交金额'),
					);
					Output::instance()->objArrayExcel('素材分享统计', $expCellName, $arr);
				}
			if ($arr) {
				$count = $MialoadModel->alias("content")
					->where($cwhere)
					->limit($start,$limit)
					->field("content.id,content.title,content.createTime")
					->count();
				Output::instance()->objArray($arr,$count);
			} else {
				Output::instance()->resultCode(code_success);
			}

		}

		/**
		 * 用户统计
		 */
		public function userStatis(){
			Session::switchCustomer(0);
			$table_statistics = M('table_statistics');
			$mishare_visit = M('mishare_visit');
			$user_statistics = M('user_statistics');
			$mishare_from = M('mishare_from');

			/**------------添加浏览次数---------------**/
			/** 1.取上一次最后浏览统计的Id */
			$view_endId['table'] = array('eq', 'share_visit');
			$view_endId['type'] = array('eq', 'user');
			$viewStartId = $table_statistics->where($view_endId)->getField('endId');
			/** 2.查询本次截至id */
			$visitEndId_where['id'] = array('gt', $viewStartId);
			$visitEndId = $mishare_visit->where($visitEndId_where)->getField('max(id)');
			if(!empty($visitEndId)){
				/** 3.最后一次浏览Id对应入库 */
				$table_statistics->where($view_endId)->setField('endId',$visitEndId);
				/** 4.查询本次统计的用户,平台,次数 */
				$visit_where['id'] = array(array('gt', $viewStartId), array('elt', $visitEndId));
				$visitArr = $mishare_visit->where($visit_where)->group('cid,uId')->field('count(*) as viewCount,uId as uid,cid')->select();
				foreach($visitArr as $value){
					if(!empty($value['uid'])){
						$resuft = $this->checkUser($value['uid'],$value['cid']);
						if($resuft){
							$data['uid'] = $value['uid'];
							$data['cid'] = $value['cid'];
							$user_statistics->add($data);
						}
						/** 5.添加普通用户浏览次数*/
						$user_statistics->where(['uid' => $value['uid'], 'cid' => $value['cid']])->setInc('viewCount', $value['viewCount']);
					}
				}


				/**------------添加分享浏览人数,分享浏览次数---------------**/
				$visit_where['visitId'] = array('neq', '');
				$userShare = $mishare_visit->where($visit_where)->field('visitId,uId as uid,id')->select();
				foreach($userShare as $value){
					if(!empty($value['uid'])){
						$shareInfo = $mishare_from->where(['visitId' => $value['visitId']])->field('uId as uid,cid')->find();
						$resuft = $this->checkUser($shareInfo['uid'],$shareInfo['cid']);
						if($resuft){
							$visitData['uid'] = $shareInfo['uid'];
							$visitData['cid'] = $shareInfo['cid'];
							$user_statistics->add($visitData);
						}
						/** 5.添加普通用户浏览次数*/
						$user_statistics->where(['uid' => $shareInfo['uid'], 'cid' => $shareInfo['cid']])->setInc('sharePv', 1);
						$countWhere['visitId'] = array('eq', $value['visitId']);
						$countWhere['uId'] = array('eq', $value['uid']);
						$countWhere['id'] = array('elt', $value['id']);
						$count = $mishare_visit->where($countWhere)->count(); //查看
						if($count == 1){
							$user_statistics->where(['uid' => $shareInfo['uid'], 'cid' => $shareInfo['cid']])->setInc('shareUv', 1);
						}
					}
				}
			}

			/**------------添加分享次数---------------**/
			/** 1.取上一次最后分享统计的Id */
			$from_endId['table'] = array('eq', 'share_from');
			$from_endId['type'] = array('eq', 'user');
			$fromStartId = $table_statistics->where($from_endId)->getField('endId');
			/** 2.查询本次截至id */
			$fromEndId_where['id'] = array('gt', $fromStartId);
			$fromEndId = $mishare_from->where($fromEndId_where)->getField('max(id)');
			if(!empty($fromEndId)){
				/** 3.最后一次分享Id对应入库 */
				$table_statistics->where($from_endId)->setField('endId',$fromEndId);
				/** 4.查询本次统计的分享总次数 */
				$sharePv_where['id'] = array(array('gt', $fromStartId), array('elt', $fromEndId));
				$shareArr = $mishare_from->where($sharePv_where)->group('cid,uId')->field('count(*) as shareCount,uId as uid,cid,count(viewCount) as sharePv')->select();
				foreach($shareArr as $value){
					if(!empty($value['uid'])){
						$resuft = $this->checkUser($value['uid'],$value['cid']);
						if($resuft){
							$data['uid'] = $value['uid'];
							$data['cid'] = $value['cid'];
							$user_statistics->add($data);
						}
						/** 5.添加 */
						$user_statistics->where(['uid' => $value['uid'], 'cid' => $value['cid']])->setInc('shareCount', $value['shareCount']);
					}
				}
			}

		}

		/**
		 * 密友统计
		 */
		public function miuStatis(){
			Session::switchCustomer(0);
			$table_statistics = M('table_statistics');
			$quan_user = M('quan_user');
			$mishare_visit = M('mishare_visit');
			$miu_statistics = M('miu_statistics');
			$miyouquan_statistics = M('miyouquan');
			$mishare_from = M('mishare_from');
			$module_product_order = M('module_product_order');
			$mimall_user = M('mimall_user');

			/**------------添加分享次数---------------**/
			/** 1.取上一次最后分享统计的Id */
			$from_endId['table'] = array('eq', 'share_from');
			$from_endId['type'] = array('eq', 'miU');
			$fromStartId = $table_statistics->where($from_endId)->getField('endId');
			/** 2.查询本次截至id */
			$fromtEndId_where['id'] = array('gt', $fromStartId);
			$fromEndId = $mishare_from->where($fromtEndId_where)->getField('max(id)');
			if(!empty($fromEndId)){
				/** 3.最后一次分享Id对应入库 */
				$table_statistics->where($from_endId)->setField('endId',$fromEndId);
				/** 4.查询本次统计的分享总次数 */
				$from_where['id'] = array(array('gt', $fromStartId), array('elt', $fromEndId));
				$fromArr = $mishare_from
					->where($from_where)
					->group('cid,uId')
					->field('count(*) as shareCount,uId as uid,cid')
					->select();
				foreach($fromArr as $value){
					if(!empty($value['uid'])){
						$from_miu_where['b.cId'] = array('eq', $value['cid']);
						$from_miu_where['a.uId'] = array('eq', $value['uid']);
						$from_miu_where['a.deleted'] = array('eq', 0);
						$userInfo = $quan_user->alias('a')->where($from_miu_where)->join('wx_miyouquan as b on a.qid=b.id')->field('qid')->find();
						if(!empty($userInfo['qid'])){
							$resuft = $this->checkMiU($value['uid'],$value['cid']);
							if($resuft){
								$data['uid'] = $value['uid'];
								$data['cid'] = $value['cid'];
								$miu_statistics->add($data);
							}
							/** 5.添加密友分享总次数*/
							$miu_statistics->where(['uid' => $value['uid'], 'cid' => $value['cid']])->setInc('shareCount', $value['shareCount']);
						}
					}
				}


			}



			/**------------添加分享浏览人数,分享浏览次数---------------**/
			/** 1.取上一次最后浏览统计的Id */
			$view_endId['table'] = array('eq', 'share_visit');
			$view_endId['type'] = array('eq', 'miU');
			/** 2.查询本次截至id */
			$viewStartId = $table_statistics->where($view_endId)->getField('endId');
			$visitEndId_where['id'] = array('gt', $viewStartId);
			$visitEndId = $mishare_visit->where($visitEndId_where)->getField('max(id)');
			if(!empty($visitEndId)){
				/** 3.修改下次截至id */
				$table_statistics->where($view_endId)->setField('endId',$visitEndId);
				/** 4.查询分享对应的visitId */
				$visitId_where['id'] = array(array('gt', $viewStartId), array('elt', $visitEndId));
				$visitId_where['visitId'] = array('neq', '');
				$userShare = $mishare_visit->where($visitId_where)->field('visitId,uId as uid,id')->select();
				/** 5.查询本次更新密友的信息 */
				foreach($userShare as $value){
					$shareInfo = $mishare_from->where(['visitId' => $value['visitId']])->field('miUid as uid,cid')->find();
					if(($value['uid'] != $shareInfo['uid']) && !empty($shareInfo['uid'])){
							$visit_miu_where['b.cId'] = array('eq', $shareInfo['cid']);
							$visit_miu_where['a.uId'] = array('eq', $shareInfo['uid']);
							$visit_miu_where['a.deleted'] = array('eq', 0);
							$userInfo = $quan_user->alias('a')->where($visit_miu_where)->join('wx_miyouquan as b on a.qid=b.id')->field('qid')->find();
							if(!empty($userInfo['qid'])){
								$resuft = $this->checkMiU($shareInfo['uid'],$shareInfo['cid']);
								if($resuft){
									$visitData['uid'] = $shareInfo['uid'];
									$visitData['cid'] = $shareInfo['cid'];
									$miu_statistics->add($visitData);
								}
								/** 6.添加普通用户浏览次数*/
								$miu_statistics->where(['uid' => $shareInfo['uid'], 'cid' => $shareInfo['cid']])->setInc('sharePv', 1);
								$countWhere['visitId'] = array('eq', $value['visitId']);
								$countWhere['uId'] = array('eq', $value['uid']);
								$countWhere['id'] = array('elt', $value['id']);
								$count = $mishare_visit->where($countWhere)->count(); //查看
								if($count == 1){
									$miu_statistics->where(['uid' => $shareInfo['uid'], 'cid' => $shareInfo['cid']])->setInc('shareUv', 1);
								}
						}
					}
				}
			}



			/** 1.取上次截至注册好友Id*/
			$miU_endId['table'] = array('eq', 'quan_user');
			$miU_endId['type'] = array('eq', 'miU');
			$miUStartId = $table_statistics->where($miU_endId)->getField('endId');
			/** 2.查询本次截至id */
			$miUEndId_where['id'] = array('gt', $miUStartId);
			$miUEndId = $quan_user->where($miUEndId_where)->getField('max(id)');
			if(!empty($miUEndId)){
				/** 3.最后一次注册好友Id对应入库 */
				$table_statistics->where($miU_endId)->setField('endId',$miUEndId);
				/** 4.查询本次统计的注册好友数 */
				$miU_where['a.id'] = array(array('gt', $miUStartId), array('elt', $miUEndId));
				$miU_where['a.deleted'] = array('eq', 0);
				$miUArr = $quan_user
					->alias('a')
					->where($miU_where)
					->join('wx_miyouquan as b on a.qid=b.id')
					->field('a.uid,a.qid,b.cId as cid')
					->select();
				foreach($miUArr as $value){
                    $three_miu = $mimall_user->where(['uId' => $value['uid'], 'qId' => $value['qid'], 'cId' => $value['cid']])->find();
                    if(!empty($three_miu['refereeUid'])){
                        $resuft = $this->checkMiU($three_miu['refereeUid'],$three_miu['cId']);
                        if($resuft){
                            $data['uid'] = $three_miu['refereeUid'];
                            $data['cid'] = $three_miu['cId'];
                            $miu_statistics->add($data);
                        }
                        $miu_statistics->where(['uid' => $three_miu['refereeUid'],'cid' =>$three_miu['cId']])->setInc('miUCount');
                    }
                    if(!empty($three_miu['preRefereeUid'])){
                        $resuft = $this->checkMiU($three_miu['preRefereeUid'],$three_miu['cId']);
                        if($resuft){
                            $data['uid'] = $value['preRefereeUid'];
                            $data['cid'] = $value['cid'];
                            $miu_statistics->add($data);
                        }
                        $miu_statistics->where(['uid' => $three_miu['preRefereeUid'],'cid' =>$three_miu['cId']])->setInc('miUCount');
                    }
				}
			}
			$quanIds = $miyouquan_statistics->getField('id',true);
			foreach($quanIds as $v){
				$count = $quan_user->where(['qid' => $v,'deleted' => 0])->count();
				$miyouquan_statistics->where(['id' => $v])->setField('miUCount',$count);
			}
			//普通好友
			$quan_user = $quan_user->alias("mi")->where(['deleted' => 0])->join('wx_miyouquan as qu on mi.qid=qu.id')->field('cid,qid,uid')->select();
			foreach($quan_user as $value){
				if($value['qid'] && $value['cid'] && $value['uid']){
                    $where_friends['mi.miUid'] = $value['uid'];
                    $where_friends['mi.refereeUid'] = $value['uid'];
                    $where_friends['mi.preRefereeUid'] = $value['uid'];
                    $where_friends['_logic'] = "OR";
                    $where_friend["_complex"] = $where_friends;
                    $where_friend["mi.qId"] = $value['qid'];
                    $where_friend["mi.uId"] = array('neq', $value['uid']);
                    $where_friend["mi.cId"] = $value['cid'];


					$friendCount = $mimall_user->alias("mi")
						->join("wx_quan_user qu on mi.uId = qu.uid and qu.qid =".$value['qid']." and qu.deleted=0")
						->where($where_friend)
						->count();
					$resuft = $this->checkMiU($value['uid'],$value['cid']);
					if($resuft){
						$data['uid'] = $value['uid'];
						$data['cid'] = $value['cid'];
						$miu_statistics->add($data);
					}
					$miu_statistics->where(['uid' => $value['uid'],'cid' =>$value['cid']])->setField('friendCount',$friendCount);
				}
			}


			$quanInfo = $miyouquan_statistics->where(['deleted' => 0])->getField('id', true);
			foreach($quanInfo as $v){
				$quanUv = $mimall_user->where(['qId' => $v])->count();
				$miyouquan_statistics->where(['id' =>$v])->setField('shareUv', $quanUv);
			}
		}

		/**
		 * 销售员统计
		 */
		public function saleSourceStatis(){
			Session::switchCustomer(0);
			$table_statistics = M('table_statistics');
			$mishare_visit = M('mishare_visit');
			$saleSource_statistics = M('salesource_statistics');
			$mishare_from = M('mishare_from');
			$module_product_order = M('module_product_order');
			$quan_user = M('quan_user');
			$mimall_user = M('mimall_user');



			$share_endId['table'] = array('eq', 'share_from');
			$share_endId['type'] = array('eq', 'saleSource');
			$shareStartId = $table_statistics->where($share_endId)->getField('endId');
			/** 2.查询本次截至id */
			$fromEndId_where['id'] = array('gt', $shareStartId);
			$fromEndId = $mishare_from->where($fromEndId_where)->getField('max(id)');
			if(!empty($fromEndId)){
				/** 3.最后一次分享Id对应入库 */
				$table_statistics->where($share_endId)->setField('endId',$fromEndId);
				/** 4.查询本次统计的分享总次数,分享浏览次数 */
				$sharePv_where['id'] = array(array('gt', $shareStartId), array('elt', $fromEndId));
				$shareArr = $mishare_from->where($sharePv_where)->group('cid,saleSourceUid')->field('count(*) as shareCount,saleSourceUid as uid,cid,count(viewCount) as sharePv')->select();
				foreach($shareArr as $value){
					if(!empty($value['uid'])){
						$resuft = $this->checkSaleSource($value['uid'],$value['cid']);
						if($resuft){
							$data['uid'] = $value['uid'];
							$data['cid'] = $value['cid'];
							$saleSource_statistics->add($data);
						}
						$saleSource_statistics->where(['uid' => $value['uid'],'cid' =>$value['cid']])->setInc('shareCount',$value['shareCount']);
					}
				}
			}

			/**------------添加分享浏览人数,分享浏览次数---------------**/
			/** 1.取上一次最后浏览统计的Id */
			$view_endId['table'] = array('eq', 'share_visit');
			$view_endId['type'] = array('eq', 'saleSource');
			/** 2.查询本次截至id */
			$viewStartId = $table_statistics->where($view_endId)->getField('endId');
			$visitEndId_where['id'] = array('gt', $viewStartId);
			$visitEndId = $mishare_visit->where($visitEndId_where)->getField('max(id)');
			if(!empty($visitEndId)){
				/** 3.修改下次截至id */
				$table_statistics->where($view_endId)->setField('endId',$visitEndId);
				/** 4.查询分享对应的visitId */
				$visitId_where['id'] = array(array('gt', $viewStartId), array('elt', $visitEndId));
				$visitId_where['visitId'] = array('neq', '');
				$userShare = $mishare_visit->where($visitId_where)->field('visitId,uId as uid,id')->select();

				/** 5.查询本次更新密友的信息 */
				foreach($userShare as $value){
					$shareInfo = $mishare_from->where(['visitId' => $value['visitId']])->field('saleSourceUid as uid,cid')->find();
					if(!empty($shareInfo['uid']) && ($shareInfo['uid'] != $value['uid'])){
						$resuft = $this->checkUser($shareInfo['uid'],$shareInfo['cid']);
						if($resuft){
							$visitData['uid'] = $shareInfo['uid'];
							$visitData['cid'] = $shareInfo['cid'];
							$saleSource_statistics->add($visitData);
						}
						/** 6.添加普通用户浏览次数*/
						$saleSource_statistics->where(['uid' => $shareInfo['uid'], 'cid' => $shareInfo['cid']])->setInc('sharePv', 1);
						$countWhere['visitId'] = array('eq', $value['visitId']);
						$countWhere['uId'] = array('eq', $value['uid']);
						$countWhere['id'] = array('elt', $value['id']);
						$count = $mishare_visit->where($countWhere)->count(); //查看
						if($count == 1){
							$saleSource_statistics->where(['uid' => $shareInfo['uid'], 'cid' => $shareInfo['cid']])->setInc('shareUv', 1);
						}
					}
				}
			}



			/** 1.取上次截至注册好友Id*/
			$miU_endId['table'] = array('eq', 'quan_user');
			$miU_endId['type'] = array('eq', 'saleSource');
			$miUStartId = $table_statistics->where($miU_endId)->getField('endId');
			/** 2.查询本次截至id */
			$miUEndId_where['id'] = array('gt', $miUStartId);
			$miUEndId = $quan_user->where($miUEndId_where)->getField('max(id)');
			if(!empty($miUEndId)){
				/** 3.最后一次注册好友Id对应入库 */
				$table_statistics->where($miU_endId)->setField('endId',$miUEndId);
			}
			/** 4.查询本次统计的注册好友数 */
			$miU_where['a.deleted'] = array('eq', 0);
			$miU_where['a.saleSource'] = array('neq', '');
			$miUArr = $quan_user
				->alias('a')
				->where($miU_where)
				->join('wx_miyouquan as b on a.qid=b.id')
				->group('cId,saleSource')
				->field('a.saleSource as uid,count(*) as miUCount,b.cId as cid')
				->select();
			foreach($miUArr as $value){
				if(!empty($value['uid'])){
					$resuft = $this->checkSaleSource($value['uid'],$value['cid']);
					if($resuft){
						$data['uid'] = $value['uid'];
						$data['cid'] = $value['cid'];
						$saleSource_statistics->add($data);
					}
					$value['miUCount'] = $value['miUCount'] -1;
					$saleSource_statistics->where(['uid' => $value['uid'],'cid' =>$value['cid']])->setField('miUCount',$value['miUCount']);
				}
			}

			//注册好友
			$quanSale = $quan_user->alias("mi")->where(['mi.deleted' => 0,'mi.isSaleSource'=>1])->join('wx_miyouquan as qu on mi.qid=qu.id')->field('cid,qid,uid')->select();
			foreach($quanSale as $value){
				if($value['qid'] && $value['cid'] && $value['uid']){
					$where_friend["mi.qId"] = $value['qid'];
					$where_friend["mi.uId"] = array('neq', $value['uid']);
					$where_friend["mi.cId"] = $value['cid'];
					$where_friend['mi.saleSource'] = $value['uid'];
					$friendCount = $mimall_user->alias("mi")
						->join("wx_quan_user qu on mi.uId = qu.uid and qu.qid =".$value['qid']." and qu.deleted=0")
						->where($where_friend)
						->count();
					$resuft = $this->checkSaleSource($value['uid'],$value['cid']);
					if($resuft){
						$data['uid'] = $value['uid'];
						$data['cid'] = $value['cid'];
						$saleSource_statistics->add($data);
					}
					$saleSource_statistics->where(['uid' => $value['uid'],'cid' =>$value['cid']])->setField('friendCount',$friendCount);
				}
			}



//			/** 1.取上次截至好友Id*/
//			$friend_endId['table'] = array('eq', 'mimall_user');
//			$friend_endId['type'] = array('eq', 'saleSource');
//			$friendStartId = $table_statistics->where($friend_endId)->getField('endId');
//			/** 2.查询本次截至id */
//			$friendEndId_where['id'] = array('gt', $friendStartId);
//			$friendEndId = $mimall_user->where($friendEndId_where)->getField('max(id)');
//			if(!empty($friendEndId)){
//				/** 3.最后一次好友Id对应入库 */
//				$table_statistics->where($friend_endId)->setField('endId',$friendEndId);
//				/** 4.查询本次统计的好友数 */
//				$friend_where['id'] = array(array('gt', $friendStartId), array('elt', $friendEndId));
//				$friendArr = $mimall_user->where($friend_where)->group('cId,saleSource')->field('saleSource as uid,count(*) as friendCount,cId as cid')->select();
//				foreach($friendArr as $value){
//					if(!empty($value['uid'])){
//						$resuft = $this->checkSaleSource($value['uid'],$value['cid']);
//						if($resuft){
//							$data['uid'] = $value['uid'];
//							$data['cid'] = $value['cid'];
//							$saleSource_statistics->add($data);
//						}
//						$saleSource_statistics->where(['uid' => $value['uid'],'cid' =>$value['cid']])->setInc('friendCount',$value['friendCount']);
//					}
//				}
//			}




		}

		/**
		 * 用户行为记录
		 */
		public function userAction(){
			Session::switchCustomer(0);
			$table_statistics = M('table_statistics');
			$mishare_visit = M('mishare_visit');
			$mishare_from = M('mishare_from');
			$module_product_order = M('module_product_order');
			$quan_user = M('quan_user');



			/**------------添加浏览记录---------------**/
			/** 1.取上一次浏览记录的Id */
			$visit_endId['table'] = array('eq', 'share_visit');
			$visit_endId['type'] = array('eq', 'action');
			$visitStartId = $table_statistics->where($visit_endId)->getField('endId');
			/** 2.查询本次截至id */
			$visitEndId_where['id'] = array('gt', $visitStartId);
			$visitEndId = $mishare_visit->where($visitEndId_where)->getField('max(id)');
			if(!empty($visitEndId)){
				/** 2.查询本次统计的浏览记录信息 */
				$visit_where['id'] = array(array('gt', $visitStartId), array('elt', $visitEndId));
				$visitArr = $mishare_visit->where($visit_where)->field('module, moduleId, uId as uid, cid as cid, createTime')->select();
				foreach($visitArr as $value){
					if(!empty($value['uid'])){
						/** 记录入库*/
						$this->addAction($value['module'],$value['moduleId'],$value['uid'],$value['cid'],$value['createTime'],'');
					}
				}
				//更新上一次浏览记录的Id
				$table_statistics->where($visit_endId)->setField('endId',$visitEndId);
			}



			/**------------添加分享记录---------------**/
			/** 1.取上一次分享记录的Id */
			$from_endId['table'] = array('eq', 'share_from');
			$from_endId['type'] = array('eq', 'action');
			$fromStartId = $table_statistics->where($from_endId)->getField('endId');
			/** 2.查询本次截至id */
			$fromEndId_where['id'] = array('gt', $fromStartId);
			$fromEndId = $mishare_from->where($fromEndId_where)->getField('max(id)');
			if(!empty($fromEndId)){
				/** 2.查询本次统计的分享记录信息 */
				$from_where['id'] = array(array('gt', $fromStartId), array('elt', $fromEndId));
				$fromArr = $mishare_from->where($from_where)->field('module, moduleId, uId as uid, cid as cid, createTime,shareType')->select();
				foreach($fromArr as $value){
					if(!empty($value['uid'])){
						/** 记录入库*/
						$this->addAction($value['module'],$value['moduleId'],$value['uid'],$value['cid'],$value['createTime'],$value['shareType'],'from');
					}
				}
				//更新上一次分享记录的Id
				$table_statistics->where($from_endId)->setField('endId',$fromEndId);
			}



			/**------------添加注册好友记录---------------**/
			/** 1.取上一次注册好友统计的Id */
			$miU_endId['table'] = array('eq', 'quan_user');
			$miU_endId['type'] = array('eq', 'action');
			$miUStartId = $table_statistics->where($miU_endId)->getField('endId');
			/** 2.查询本次截至id */
			$miUEndId_where['id'] = array('gt', $miUStartId);
			$miUEndId = $quan_user->where($miUEndId_where)->getField('max(id)');
			if(!empty($miUEndId)){
				/** 3.查询本次统计的注册好友数 */
				$miU_where['a.id'] = array(array('gt', $miUStartId),array('elt', $miUEndId));
				$miUArr = $quan_user
					->alias('a')
					->where($miU_where)
					->join('wx_miyouquan as b on a.qid=b.id')
					->field('b.cid,a.refereeUid as miUid,a.uid,a.createTime')
					->select();
				foreach($miUArr as $value){
					if(!empty($value['miUid'])){
						/** 4.调取方法添加 */
						$this->recommendMiU ($value['miUid'],$value['cid'],$value['uid'],$value['createTime']);
					}
				}
				/** 5.最后一次分享Id对应入库 */
				$table_statistics->where($miU_endId)->setField('endId',$miUEndId);
			}





			/**------------添加购买记录---------------**/
			/** 1.取上一次订单统计的Id */
			$order_endId['table'] = array('eq', 'module_product_order');
			$order_endId['type'] = array('eq', 'action');
			$orderStartId = $table_statistics->where($order_endId)->getField('endId');
			/** 2.查询本次截至id */
			$orderEndId_where['id'] = array('gt', $orderStartId);
			$orderEndId = $module_product_order->where($orderEndId_where)->getField('max(id)');
			if(!empty($orderEndId)){
				/** 3.查询本次统计的订单数,总销售额 */
				$order_where['id'] = array(array('gt', $orderStartId), array('elt', $orderEndId));
//				$order_where['status'] = array(array('eq', 'ok'), array('eq', 'delivering'), array('eq', 'delivered'), 'or');
				$orderArr = $module_product_order->where($order_where)->field('id,uId as uid,fromCustomerId as cid,createTime,type')->select();
				foreach($orderArr as $value){
					if($value['uid'] != 0){
						/** 4.调取方法添加 */
						$this->buyAdd($value['uid'],$value['cid'],$value['id'],$value['createTime'],$value['type']);
					}
				}
				/** 5.最后一次订单Id对应入库 */
				$table_statistics->where($order_endId)->setField('endId',$orderEndId);
			}

		}

		/**
		 * 添加浏览,分享记录
		 * @param $module		模块
		 * @param $moduleId		模块id
		 * @param $uid			用户id
		 * @param $cid			cid
		 * @param $action		执行时间
		 * @param string $type	类型visit-浏览/from-分享
		 */
		public function addAction($module,$moduleId,$uid,$cid,$action,$shareType,$type='visit'){
			$user_action = M('user_action');
			$module_product = M('module_product');
			$micontent = M('micontent');
			switch($module){
				case 'product':
					$type == 'visit' ? $data['event'] = productView : $data['event'] = productShare;
					$info = $module_product->where("id=$moduleId")->find();

					break;
				case 'mall':
					$type == 'visit' ? $data['event'] = mallView : $data['event'] = mallShare;
					$info = M('wx_'. $cid .'material')->where("id=$moduleId")->find();
					break;
				case 'micontent':
					$type == 'visit' ? $data['event'] = miContentView : $data['event'] = miContentShare;
					$info = $micontent->where("id=$moduleId")->find();
					break;
				default:return;break;
			}
			$info['shareType'] = $shareType;
			$data['params'] = json_encode($info);
			$data['cid'] = $cid;
			$data['uid'] = $uid;
			$data['actionTime'] = $action;
			$data['createTime'] = date('Y-m-d H:i:s');
			$user_action->add($data);
		}

		/**
		 * 推荐好友记录入库
		 * @param $miUid	用户id
		 * @param $cid		cid
		 * @param $uid		推荐好友id
		 * @param $action	执行时间
		 */
		public function recommendMiU($miUid, $cid, $uid,$action){
			$user_action = M('user_action');
			$userInfo = M($cid.'_user')->where("id=$uid")->find();
			$userInfo['nickName'] = M('quan_user')->alias('a')->where(['a.uid' => $uid, 'b.cid' => $cid])->join('wx_miyouquan as b on a.qid=b.id')->getField('nickName');

			$data['cid'] = $cid;
			$data['uid'] = $miUid;
			$data['event'] = recommendMiU;
			$data['actionTime'] = $action;
			$data['createTime'] = date('Y-m-d H:i:s');
			$data['params'] = json_encode($userInfo);;
			$user_action->add($data);
		}

		/**
	 * 添加购买记录
	 * @param $uid		用户id
	 * @param $cid		cid
	 * @param $oid		订单id
	 * @param $action	执行时间
	 */
		public function buyAdd($uid,$cid,$oid,$action,$type){
			$module_product_order_detail = M('module_product_order_detail');
			$user_action = M('user_action');
			$orderInfo = $module_product_order_detail->where("oid=$oid")->find();
			$data['cid'] = $cid;
			$data['uid'] = $uid;
			$data['event'] = buy ;
			$data['actionTime'] = $action;
			$data['createTime'] = date('Y-m-d H:i:s');
			$data['params'] = json_encode($orderInfo);
			$user_action->add($data);
		}

		//检查普通用户是否存在
		public function checkUser($uid,$cid){
			Session::switchCustomer(0);
			$user_statistics = M('user_statistics');
			$user = $user_statistics->where(['uid' => $uid, 'cid'=> $cid])->find();
			if(empty($user)){
				return true;
			}
			return false;
		}
		//检查密友是否存在
		public function checkMiU($uid,$cid){
			Session::switchCustomer(0);
			$miu_statistics = M('miu_statistics');
			$user = $miu_statistics->where(['uid' => $uid, 'cid'=> $cid])->find();
			if(empty($user)){
				return true;
			}
			return false;
		}
		//检查销售源是否存在
		public function checkSaleSource($uid,$cid){
			Session::switchCustomer(0);
			$salesource_statistics = M('salesource_statistics');
			$user = $salesource_statistics->where(['uid' => $uid, 'cid'=> $cid])->find();
			if(empty($user)){
				return true;
			}
			return false;
		}


	/**
	 * 订单统计增加
	 */
	public function orderSuccessStatis(){
		Session::switchCustomer(0);
		$orderModel = M('module_product_order');
		$miu_statistics = M('miu_statistics');
		$saleSource_statistics = M('salesource_statistics');
		$ProductOrderModel = M("");
		$redis = new RedisAPI();
		$max = $redis->lLen("orderSuccess_log");
		$arr = $redis->LRANGE("orderSuccess_log",0,-1);
		$count = 0;
		while ($count < $max) {
			$count++;
			$oid = $redis->lPop("orderSuccess_log");
			if ($oid == 'nil' || !isset($oid)) {
				continue;
			}
			$orderInfo = $orderModel->where(['id' => $oid])->field('qId,uId,miUid,refereeUid,parentRefereeUid,price,saleSource,fromCustomerId')->find();
			$price = $orderInfo['price'];
			$miUid = $orderInfo['miUid'];
			$referrrUid = $orderInfo['refereeUid'];
			$parentRefereree = $orderInfo['parentRefereeUid'];
			$saleSource = $orderInfo['saleSource'];
			$cid = $orderInfo['fromCustomerId'];
			$uId = $orderInfo['uId'];
          	$qId = $orderInfo['qId'];
			$ProductOrderModel->startTrans();
			if($miUid){         //注册好友添加订单数量
				$res = $this->checkMiU($miUid,$cid);
				if($res){
					$data['uid'] = $miUid;
					$data['cid'] = $cid;
					$miu_statistics->add($data);
				}
				$query = "UPDATE wx_miu_statistics SET orderCount = orderCount + 1 WHERE cid = $cid AND uid  = $miUid";
				$result = $ProductOrderModel->query($query);
				if ($result === false) {
					Log::write("注册好友添加订单数量错误:".$ProductOrderModel->getLastSql());
					$redis->rPush("order_log", $oid);
					$ProductOrderModel->rollback();
					continue;
				}
			}
			if($referrrUid){    //推荐人添加订单数量
				$res = $this->checkMiU($referrrUid,$cid);
				if($res){
					$data['uid'] = $referrrUid;
					$data['cid'] = $cid;
					$miu_statistics->add($data);
				}
				$query = "UPDATE wx_miu_statistics SET orderCount = orderCount + 1 WHERE cid = $cid AND uid  = $referrrUid";
				$result = $ProductOrderModel->query($query);
				if ($result === false) {
					Log::write("推荐人添加订单数量错误:".$ProductOrderModel->getLastSql());
					$redis->rPush("order_log", $oid);
					$ProductOrderModel->rollback();
					continue;
				}
			}
			if($parentRefereree){           //上级推荐人添加订单数量
				$res = $this->checkMiU($parentRefereree,$cid);
				if($res){
					$data['uid'] = $parentRefereree;
					$data['cid'] = $cid;
					$miu_statistics->add($data);
				}
				$query = "UPDATE wx_miu_statistics SET orderCount = orderCount + 1 WHERE cid = $cid AND uid  = $parentRefereree";
				$result = $ProductOrderModel->query($query);
				if ($result === false) {
					Log::write("上级推荐人添加订单数量错误:".$ProductOrderModel->getLastSql());
					$redis->rPush("order_log", $oid);
					$ProductOrderModel->rollback();
					continue;
				}
			}
			if($saleSource){                //销售员添加订单数量
				$res = $this->checkSaleSource($saleSource,$cid);
				if($res){
					$data['uid'] = $saleSource;
					$data['cid'] = $cid;
					$saleSource_statistics->add($data);
				}
				$query = "UPDATE wx_salesource_statistics SET orderCount = orderCount + 1 WHERE cid = $cid AND uid  = $saleSource";
				$result = $ProductOrderModel->query($query);
				if ($result === false) {
					Log::write("销售员添加订单数量错误:".$ProductOrderModel->getLastSql());

					$redis->rPush("order_log", $oid);
					$ProductOrderModel->rollback();
					continue;
				}
			}
          	if($qId){
				$query = "UPDATE wx_miyouquan SET orderCount = orderCount + 1 WHERE cid = $cid AND id  = $qId";
				$result = $ProductOrderModel->query($query);
				if ($result === false) {
					Log::write("营销圈添加订单数量错误:".$ProductOrderModel->getLastSql());
					$redis->rPush("order_log", $oid);
					$ProductOrderModel->rollback();
					continue;
				}
			}

			if($orderInfo['price'] > 0  &&  $miUid){   //注册好友添加订单金额数量
				$res = $this->checkMiU($miUid,$cid);
				if($res){
					$data['uid'] = $miUid;
					$data['cid'] = $cid;
					$miu_statistics->add($data);
				}
				$query = "UPDATE wx_miu_statistics SET orderPrice = orderPrice + $price WHERE cid = $cid AND uid  = $miUid";
				$result = $ProductOrderModel->query($query);
				if ($result === false) {
					$redis->rPush("order_log", $oid);
					$ProductOrderModel->rollback();
					continue;
				}
			}
			if($orderInfo['price'] > 0  &&  $referrrUid){   //推荐人添加订单金额数量
				$res = $this->checkMiU($referrrUid,$cid);
				if($res){
					$data['uid'] = $referrrUid;
					$data['cid'] = $cid;
					$miu_statistics->add($data);
				}
				$query = "UPDATE wx_miu_statistics SET orderPrice = orderPrice + $price WHERE cid = $cid AND uid  = $referrrUid";
				$result = $ProductOrderModel->query($query);
				if ($result === false) {
					$redis->rPush("order_log", $oid);
					$ProductOrderModel->rollback();
					continue;
				}
			}
			if($orderInfo['price'] > 0  &&  $parentRefereree){      //上级推荐人添加订单金额数量
				$res = $this->checkMiU($parentRefereree,$cid);
				if($res){
					$data['uid'] = $parentRefereree;
					$data['cid'] = $cid;
					$miu_statistics->add($data);
				}
				$query = "UPDATE wx_miu_statistics SET orderPrice = orderPrice + $price WHERE cid = $cid AND uid  = $parentRefereree";
				$result = $ProductOrderModel->query($query);
				if ($result === false) {
					$redis->rPush("order_log", $oid);
					$ProductOrderModel->rollback();
					continue;
				}
			}
			if($orderInfo['price'] > 0  &&  $saleSource){    //销售员添加订单金额数量
				$res = $this->checkSaleSource($saleSource,$cid);
				if($res){
					$data['uid'] = $saleSource;
					$data['cid'] = $cid;
					$saleSource_statistics->add($data);
				}
				$query = "UPDATE wx_salesource_statistics SET orderPrice = orderPrice + $price WHERE cid = $cid AND uid  = $saleSource";
				$result = $ProductOrderModel->query($query);
				if ($result === false) {
					$redis->rPush("order_log", $oid);
					$ProductOrderModel->rollback();
					continue;
				}
			}
            if($orderInfo['price'] > 0  &&  $qId){
				$query = "UPDATE wx_miyouquan SET orderPrice = orderPrice + $price WHERE cid = $cid AND id  = $qId";
				$result = $ProductOrderModel->query($query);
				if ($result === false) {
					Log::write("营销圈添加订单金额错误:".$ProductOrderModel->getLastSql());
					$redis->rPush("order_log", $oid);
					$ProductOrderModel->rollback();
					continue;
				}
			}
			$ProductOrderModel->commit();
		}
	}
	/**
	 * 订单统计退款减少
	 */
	public function orderRefundStatis()
	{
		Session::switchCustomer(0);
		$orderModel = M('module_product_order');
		$ProductOrderModel = M("");
		$redis = new RedisAPI();
		$max = $redis->lLen("orderRefund_log");
		$arr = $redis->LRANGE("orderRefund_log", 0, -1);
		echo $max;
		print_r($arr);
		$count = 0;
		while ($count < $max) {
			$count++;
			$value = $redis->lPop("orderRefund_log");
			if ($value == 'nil' || !isset($value)) {
				continue;
			}
			$arr = implode(',', $value);
			$oid = $arr[0];
			$price = $arr[1];
			$refundStatus = $arr[2];


			$orderInfo = $orderModel->where(['id' => $oid])->field('qId,uId,miUid,refereeUid,parentRefereeUid,saleSource,fromCustomerId')->find();
			$miUid = $orderInfo['miUid'];
			$referrrUid = $orderInfo['refereeUid'];
			$parentRefereree = $orderInfo['parentRefereeUid'];
			$saleSource = $orderInfo['saleSource'];
			$cid = $orderInfo['fromCustomerId'];
			$uId = $orderInfo['uId'];
          	$qId = $orderInfo['qId'];
			$ProductOrderModel->startTrans();
			if($refundStatus == order_status_refund){
				if($miUid){         //注册好友退款减少订单数量
					$query = "UPDATE wx_miu_statistics SET orderCount = orderCount - 1 WHERE cid = $cid AND uid  = $miUid";
					$result = $ProductOrderModel->query($query);
					if ($result === false) {
						Log::write("注册好友退款减少订单数量错误:".$ProductOrderModel->getLastSql());
						$redis->rPush("orderRefund_log", $oid.','.$price.','.$refundStatus);
						$ProductOrderModel->rollback();
						continue;
					}
				}
				if($referrrUid){    //推荐人退款减少订单数量
					$query = "UPDATE wx_miu_statistics SET orderCount = orderCount - 1 WHERE cid = $cid AND uid  = $referrrUid";
					$result = $ProductOrderModel->query($query);
					if ($result === false) {
						Log::write("推荐人退款减少订单数量错误:".$ProductOrderModel->getLastSql());
						$redis->rPush("orderRefund_log", $oid.','.$price.','.$refundStatus);
						$ProductOrderModel->rollback();
						continue;
					}
				}
				if($parentRefereree){           //上级推荐人退款减少订单数量
					$query = "UPDATE wx_miu_statistics SET orderCount = orderCount - 1 WHERE cid = $cid AND uid  = $parentRefereree";
					$result = $ProductOrderModel->query($query);
					if ($result === false) {
						Log::write("上级推荐人添退款减少订单数量错误:".$ProductOrderModel->getLastSql());
						$redis->rPush("orderRefund_log", $oid.','.$price.','.$refundStatus);
						$ProductOrderModel->rollback();
						continue;
					}
				}
				if($saleSource){                //销售员退款减少订单数量
					$query = "UPDATE wx_salesource_statistics SET orderCount = orderCount - 1 WHERE cid = $cid AND uid  = $saleSource";
					$result = $ProductOrderModel->query($query);
					if ($result === false) {
						Log::write("销售员退款减少订单数量错误:".$ProductOrderModel->getLastSql());
						$redis->rPush("orderRefund_log", $oid.','.$price.','.$refundStatus);
						$ProductOrderModel->rollback();
						continue;
					}
				}
              	if($qId){                //营销圈退款减少订单数量
					$query = "UPDATE wx_miyouquan SET orderCount = orderCount - 1 WHERE id  = $qId";
					$result = $ProductOrderModel->query($query);
					if ($result === false) {
						Log::write("营销圈退款减少订单数量错误:".$ProductOrderModel->getLastSql());
						$redis->rPush("orderRefund_log", $oid.','.$price.','.$refundStatus);
						$ProductOrderModel->rollback();
						continue;
					}
				}
			}


			if($price > 0  &&  $miUid){   //注册好友退款减少订单金额数量
				$query = "UPDATE wx_miu_statistics SET orderPrice = orderPrice - $price WHERE cid = $cid AND uid  = $miUid";
				$result = $ProductOrderModel->query($query);
				if ($result === false) {
					Log::write("注册好友退款减少金额数量错误:".$ProductOrderModel->getLastSql());
					$redis->rPush("orderRefund_log", $oid.','.$price.','.$refundStatus);
					$ProductOrderModel->rollback();
					continue;
				}
			}
			if($price > 0  &&  $referrrUid){   //推荐人退款减少订单金额数量
				$query = "UPDATE wx_miu_statistics SET orderPrice = orderPrice - $price WHERE cid = $cid AND uid  = $referrrUid";
				$result = $ProductOrderModel->query($query);
				if ($result === false) {
					Log::write("推荐人退款减少订单金额数量错误:".$ProductOrderModel->getLastSql());
					$redis->rPush("orderRefund_log", $oid.','.$price.','.$refundStatus);
					$ProductOrderModel->rollback();
					continue;
				}
			}
			if($price > 0  &&  $parentRefereree){      //上级推荐人退款减少订单金额数量
				$query = "UPDATE wx_miu_statistics SET orderPrice = orderPrice - $price WHERE cid = $cid AND uid  = $parentRefereree";
				$result = $ProductOrderModel->query($query);
				if ($result === false) {
					Log::write("上级推荐人退款减少订单金额数量:".$ProductOrderModel->getLastSql());
					$redis->rPush("orderRefund_log", $oid.','.$price.','.$refundStatus);
					$ProductOrderModel->rollback();
					continue;
				}
			}
			if($price > 0  &&  $saleSource){    //销售员退款减少订单金额数量
				$query = "UPDATE wx_salesource_statistics SET orderPrice = orderPrice - $price WHERE cid = $cid AND uid  = $saleSource";
				$result = $ProductOrderModel->query($query);
				if ($result === false) {
					Log::write("销售员退款减少订单金额数量数量:".$ProductOrderModel->getLastSql());
					$redis->rPush("orderRefund_log", $oid.','.$price.','.$refundStatus);
					$ProductOrderModel->rollback();
					continue;
				}
			}
          if($price > 0  &&  $qId){    //营销圈退款减少订单金额数量
				$query = "UPDATE wx_miyouquan SET orderPrice = orderPrice - $price WHERE id  = $qId";
				$result = $ProductOrderModel->query($query);
				if ($result === false) {
					Log::write("营销圈退款减少订单金额:".$ProductOrderModel->getLastSql());
					$redis->rPush("orderRefund_log", $oid.','.$price.','.$refundStatus);
					$ProductOrderModel->rollback();
					continue;
				}
			}


			$ProductOrderModel->commit();

		}
	}

    /**
     * 订单成交进行统计
     * @param $idArray
     * @param $customerId
     */
	public function statisOrder($idArray, $customerId){
        Session::switchCustomer(0);
        $miu_statistics = M('miu_statistics');
        $saleSource_statistics = M('salesource_statistics');
        $ProductOrderModel = M("");
        $OrderModel = M("module_product_order");
        Session::switchCustomer($customerId);
        foreach ($idArray as $key => $value){
            $module = 'order';
            $moduleId = $oid = $value;
            $orderInfo = $OrderModel->where(['id' => $oid])->field('qId,uId,miUid,refereeUid,parentRefereeUid,price,saleSource,fromCustomerId,type,points')->find();
            $price = $orderInfo['price'];
            $miUid = $orderInfo['miUid'];
            $referrrUid = $orderInfo['refereeUid'];
            $parentRefereree = $orderInfo['parentRefereeUid'];
            $saleSource = $orderInfo['saleSource'];
            $cid = $orderInfo['fromCustomerId'];
            $uId = $orderInfo['uId'];
            $qId = $orderInfo['qId'];
            $orderType = $orderInfo['type'];
            $points = $orderInfo['points'];
            if ( $orderType == 'buy' ){
                $countField = 'buyOrderCount';
                $priceField = 'buyOrderPrice';
            }elseif($orderType == 'form'){
                $countField = 'formOrderCount';
                $priceField = 'formOrderPrice';
            }elseif ($orderType == 'point'){
                $countField = 'pointOrderCount';
                $priceField = 'pointOrderPoint';
                $price = $points;
            }
            $ProductOrderModel->startTrans();
            if($miUid){         //注册好友添加订单数量
                $res = self::checkMiU($miUid,$cid);
                if($res){
                    $data['uid'] = $miUid;
                    $data['cid'] = $cid;
                    $miu_statistics->add($data);
                }
                $query = "UPDATE wx_miu_statistics SET $countField = $countField + 1 WHERE cid = $cid AND uid  = $miUid";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("注册好友添加订单数量错误:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'fail',$cid);
                    continue;
                }
            }
            if($referrrUid){    //推荐人添加订单数量
                $res = self::checkMiU($referrrUid,$cid);
                if($res){
                    $data['uid'] = $referrrUid;
                    $data['cid'] = $cid;
                    $miu_statistics->add($data);
                }
                $query = "UPDATE wx_miu_statistics SET $countField = $countField + 1 WHERE cid = $cid AND uid  = $referrrUid";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("推荐人添加订单数量错误:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'fail',$cid);
                    continue;
                }
            }
            if($parentRefereree){           //上级推荐人添加订单数量
                $res = self::checkMiU($parentRefereree,$cid);
                if($res){
                    $data['uid'] = $parentRefereree;
                    $data['cid'] = $cid;
                    $miu_statistics->add($data);
                }
                $query = "UPDATE wx_miu_statistics SET $countField = $countField + 1 WHERE cid = $cid AND uid  = $parentRefereree";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("上级推荐人添加订单数量错误:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'fail',$cid);
                    continue;
                }
            }
            if($saleSource){                //销售员添加订单数量
                $res = self::checkSaleSource($saleSource,$cid);
                if($res){
                    $data['uid'] = $saleSource;
                    $data['cid'] = $cid;
                    $saleSource_statistics->add($data);
                }
                $query = "UPDATE wx_salesource_statistics SET $countField = $countField + 1 WHERE cid = $cid AND uid  = $saleSource";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("销售员添加订单数量错误:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'fail',$cid);
                    continue;
                }
            }
            if($qId){
                $query = "UPDATE wx_miyouquan SET $countField = $countField + 1 WHERE cid = $cid AND id  = $qId";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("营销圈添加订单数量错误:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'fail',$cid);
                    continue;
                }
            }

            if(($orderInfo['price'] || $orderInfo['points']) > 0  &&  $miUid){   //注册好友添加订单金额数量
                $res = self::checkMiU($miUid,$cid);
                if($res){
                    $data['uid'] = $miUid;
                    $data['cid'] = $cid;
                    $miu_statistics->add($data);
                }
                $query = "UPDATE wx_miu_statistics SET $priceField = $priceField + $price WHERE cid = $cid AND uid  = $miUid";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("注册好友添加订单金额数量:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'fail',$cid);
                    continue;
                }
            }
            if(($orderInfo['price'] || $orderInfo['points'])  &&  $referrrUid){   //推荐人添加订单金额数量
                $res = self::checkMiU($referrrUid,$cid);
                if($res){
                    $data['uid'] = $referrrUid;
                    $data['cid'] = $cid;
                    $miu_statistics->add($data);
                }
                $query = "UPDATE wx_miu_statistics SET $priceField = $priceField + $price WHERE cid = $cid AND uid  = $referrrUid";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("推荐人添加订单金额数量:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'fail',$cid);
                    continue;
                }
            }
            if(($orderInfo['price'] || $orderInfo['points'])  &&  $parentRefereree){      //上级推荐人添加订单金额数量
                $res = self::checkMiU($parentRefereree,$cid);
                if($res){
                    $data['uid'] = $parentRefereree;
                    $data['cid'] = $cid;
                    $miu_statistics->add($data);
                }
                $query = "UPDATE wx_miu_statistics SET $priceField = $priceField + $price WHERE cid = $cid AND uid  = $parentRefereree";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("级推荐人添加订单金额数量:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'fail',$cid);
                    continue;
                }
            }
            if(($orderInfo['price'] || $orderInfo['points'])  &&  $saleSource){    //销售员添加订单金额数量
                $res = self::checkSaleSource($saleSource,$cid);
                if($res){
                    $data['uid'] = $saleSource;
                    $data['cid'] = $cid;
                    $saleSource_statistics->add($data);
                }
                $query = "UPDATE wx_salesource_statistics SET $priceField = $priceField + $price WHERE cid = $cid AND uid  = $saleSource";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("销售员添加订单金额数量:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'fail',$cid);
                    continue;
                }
            }
            if(($orderInfo['price'] || $orderInfo['points'])  &&  $qId){
                $query = "UPDATE wx_miyouquan SET $priceField = $priceField + $price WHERE cid = $cid AND id  = $qId";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("营销圈添加订单金额错误:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'fail',$cid);
                    continue;
                }
            }
            $ProductOrderModel->commit();
            self::statisStatus($module,$moduleId,$orderType,'success',$cid);

        }

    }

    /**
     * 订单统计记录
     * @param $module       模块
     * @param $moduleId     模块id
     * @param $type         类型
     * @param $status       状态ok成功/fail失败
     * @param $cid          平台id
     */
    public function statisStatus($module,$moduleId,$type,$status,$cid,$sql){
        Session::switchCustomer(0);
        $statisStatusModel = M('statis_status');
        Session::switchCustomer($cid);
        $staData['module'] = $module;
        $staData['moduleId'] = $moduleId;
        $staData['type'] = $type;
        $staData['cid'] = $cid;
        $staData['status'] = $status;
        $staData['errorSql'] = $sql;
        $staData['createTime'] = date("Y-m-d H:i:s");
        $statisStatusModel->add($staData);
    }

    /**
     * 订单退款删除统计
     * @param $idArray
     * @param $customerId
     */
    public function statisOrderDelete($oid, $refundStatus, $customerId)
    {
        Session::switchCustomer(0);
        $OrderModel = M('module_product_order');
        $ProductOrderModel = M("");
        $module = 'order';
        $moduleId = $oid;
        $orderInfo = $OrderModel->where(['id' => $oid])->field('qId,uId,miUid,refereeUid,parentRefereeUid,price,saleSource,fromCustomerId,type,points')->find();
        $price = $orderInfo['price'];
        $miUid = $orderInfo['miUid'];
        $referrrUid = $orderInfo['refereeUid'];
        $parentRefereree = $orderInfo['parentRefereeUid'];
        $saleSource = $orderInfo['saleSource'];
        $cid = $orderInfo['fromCustomerId'];
        $uId = $orderInfo['uId'];
        $qId = $orderInfo['qId'];
        $orderType = $orderInfo['type'];
        $points = $orderInfo['points'];
        if ( $orderType == 'buy' ){
            $countField = 'buyOrderCount';
            $priceField = 'buyOrderPrice';
        }elseif($orderType == 'form'){
            $countField = 'formOrderCount';
            $priceField = 'formOrderPrice';
        }elseif ($orderType == 'point'){
            $countField = 'pointOrderCount';
            $priceField = 'pointOrderPoint';
            $price = $points;
        }
            $ProductOrderModel->startTrans();
            if($refundStatus == order_status_refund){
                if($miUid){         //注册好友退款减少订单数量
                    $query = "UPDATE wx_miu_statistics SET $countField = $countField - 1 WHERE cid = $cid AND uid  = $miUid";
                    $result = $ProductOrderModel->query($query);
                    if ($result === false) {
                        Log::write("注册好友退款减少订单数量错误:".$ProductOrderModel->getLastSql());
                        $ProductOrderModel->rollback();
                        self::statisStatus($module,$moduleId,$orderType,'refundFail',$cid,"注册好友退款减少订单数量错误:".$ProductOrderModel->getLastSql());
                        return;
                    }
                }
                if($referrrUid){    //推荐人退款减少订单数量
                    $query = "UPDATE wx_miu_statistics SET $countField = $countField - 1 WHERE cid = $cid AND uid  = $referrrUid";
                    $result = $ProductOrderModel->query($query);
                    if ($result === false) {
                        Log::write("推荐人退款减少订单数量错误:".$ProductOrderModel->getLastSql());
                        $ProductOrderModel->rollback();
                        self::statisStatus($module,$moduleId,$orderType,'refundFail',$cid,"推荐人退款减少订单数量错误:".$ProductOrderModel->getLastSql());
                        return;
                    }
                }
                if($parentRefereree){           //上级推荐人退款减少订单数量
                    $query = "UPDATE wx_miu_statistics SET $countField = $countField - 1 WHERE cid = $cid AND uid  = $parentRefereree";
                    $result = $ProductOrderModel->query($query);
                    if ($result === false) {
                        Log::write("上级推荐人添退款减少订单数量错误:".$ProductOrderModel->getLastSql());
                        $ProductOrderModel->rollback();
                        self::statisStatus($module,$moduleId,$orderType,'refundFail',$cid,"上级推荐人添退款减少订单数量错误:".$ProductOrderModel->getLastSql());
                        return;
                    }
                }
                if($saleSource){                //销售员退款减少订单数量
                    $query = "UPDATE wx_salesource_statistics SET $countField = $countField - 1 WHERE cid = $cid AND uid  = $saleSource";
                    $result = $ProductOrderModel->query($query);
                    if ($result === false) {
                        Log::write("销售员退款减少订单数量错误:".$ProductOrderModel->getLastSql());
                        $ProductOrderModel->rollback();
                        self::statisStatus($module,$moduleId,$orderType,'refundFail',$cid,"销售员退款减少订单数量错误:".$ProductOrderModel->getLastSql());
                        return;
                    }
                }
                if($qId){                //营销圈退款减少订单数量
                    $query = "UPDATE wx_miyouquan SET $countField = $countField - 1 WHERE id  = $qId";
                    $result = $ProductOrderModel->query($query);
                    if ($result === false) {
                        Log::write("营销圈退款减少订单数量错误:".$ProductOrderModel->getLastSql());
                        $ProductOrderModel->rollback();
                        self::statisStatus($module,$moduleId,$orderType,'refundFail',$cid,"营销圈退款减少订单数量错误:".$ProductOrderModel->getLastSql());
                        return;
                    }
                }
            }


            if($price > 0  &&  $miUid){   //注册好友退款减少订单金额数量
                $query = "UPDATE wx_miu_statistics SET $priceField = $priceField - $price WHERE cid = $cid AND uid  = $miUid";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("注册好友退款减少金额数量错误:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'refundFail',$cid,"注册好友退款减少金额数量错误:".$ProductOrderModel->getLastSql());
                    return;
                }
            }
            if($price > 0  &&  $referrrUid){   //推荐人退款减少订单金额数量
                $query = "UPDATE wx_miu_statistics SET $priceField = $priceField - $price WHERE cid = $cid AND uid  = $referrrUid";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("推荐人退款减少订单金额数量错误:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'refundFail',$cid,"推荐人退款减少订单金额数量错误:".$ProductOrderModel->getLastSql());
                    return;
                }
            }
            if($price > 0  &&  $parentRefereree){      //上级推荐人退款减少订单金额数量
                $query = "UPDATE wx_miu_statistics SET $priceField = $priceField - $price WHERE cid = $cid AND uid  = $parentRefereree";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("上级推荐人退款减少订单金额数量:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'refundFail',$cid,"推荐人退款减少订单金额数量错误:".$ProductOrderModel->getLastSql());
                    return;
                }
            }
            if($price > 0  &&  $saleSource){    //销售员退款减少订单金额数量
                $query = "UPDATE wx_salesource_statistics SET $priceField = $priceField - $price WHERE cid = $cid AND uid  = $saleSource";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("销售员退款减少订单金额数量数量:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'refundFail',$cid,"销售员退款减少订单金额数量数量:".$ProductOrderModel->getLastSql());
                    return;
                }
            }
            if($price > 0  &&  $qId){    //营销圈退款减少订单金额数量
                $query = "UPDATE wx_miyouquan SET $priceField = $priceField - $price WHERE id  = $qId";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("营销圈退款减少订单金额:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'refundFail',$cid,"营销圈退款减少订单金额:".$ProductOrderModel->getLastSql());
                    return;
                }
            }
            $ProductOrderModel->commit();
            self::statisStatus($module,$moduleId,$orderType,'refundSuccess',$cid);

    }

    /**
     * @param $where            修改条件
     * @param $data             添加的数据
     * @param $customerId       cid
     * @param int $isDelete     是否需要扣除统计人数
     * @return bool
     */
    public function miMallUserSave($where, $data ,$customerId, $isDelete = 0 ){
        Session::switchCustomer(0);
        $miMallUserModel = M("mimall_user");
        Session::switchCustomer($customerId);
        if(empty($where)){
            $mimaId = $miMallUserModel->add($data);
            self::friendsNumber($mimaId, $customerId);
            return true;
        }else{
            $mimaId = $miMallUserModel->where($where)->getField('id');
            if($isDelete){
                self::reduceFriendsNumber($mimaId, $customerId);
            }
            $miMallUserModel->where($where)->save($data);
//            self::friendsNumber($mimaId, $customerId);
        }
    }

    /**
     * 添加注册好友/普通好友数量
     * @param $mimaId           mimall_user主键id
     * @param $customerId       cid
     */
    public function friendsNumber($mimaId, $customerId){
        Session::switchCustomer(0);
        $miMallUserModel = M("mimall_user");
        $quanUserModel = M("quan_user");
        $miu_statistics = M('miu_statistics');
        $saleSource_statistics = M('salesource_statistics');
        $ProductOrderModel = M();
        Session::switchCustomer($customerId);
        $miUserInfo = $miMallUserModel->where(['id' => $mimaId])->find();
        $module = 'mimall';
        $moduleId = $mimaId;
        $uid = $miUserInfo['uId'];
        $miUid = $miUserInfo['miUid'];
        $referrrUid = $miUserInfo['refereeUid'];
        $parentRefereree = $miUserInfo['preRefereeUid'];
        $saleSource = $miUserInfo['saleSource'];
        $cid = $miUserInfo['cId'];
        $qId = $miUserInfo['qId'];
        $isMiu = $quanUserModel->where(['uid' => $uid, 'qid' => $qId, 'deleted' => 0])->count();
        $ProductOrderModel->startTrans();
        if($isMiu){
            if(($uid != $miUid || empty($uid)) && $miUid){
                $res = self::checkMiU($miUid,$cid);
                if($res){
                    $data['uid'] = $miUid;
                    $data['cid'] = $cid;
                    $miu_statistics->add($data);
                }
                $query = "UPDATE wx_miu_statistics SET miUCount = miUCount + 1 WHERE cid = $cid AND uid  = $miUid";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("注册好友增加注册好友数失败:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,'','addFail',$cid,"注册好友增加注册好友数失败:".$ProductOrderModel->getLastSql());
                    return;
                 }
            }
            if ($referrrUid){
                $res = self::checkMiU($referrrUid,$cid);
                if($res){
                    $data['uid'] = $referrrUid;
                    $data['cid'] = $cid;
                    $miu_statistics->add($data);
                }
                $query = "UPDATE wx_miu_statistics SET miUCount = miUCount + 1 WHERE cid = $cid AND uid  = $referrrUid";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("推荐人增加注册好友数失败:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,'','addFail',$cid,"推荐人增加注册好友数失败:".$ProductOrderModel->getLastSql());
                    return;
                }
            }
            if ($parentRefereree){
                $res = self::checkMiU($parentRefereree,$cid);
                if($res){
                    $data['uid'] = $parentRefereree;
                    $data['cid'] = $cid;
                    $miu_statistics->add($data);
                }
                $query = "UPDATE wx_miu_statistics SET miUCount = miUCount + 1 WHERE cid = $cid AND uid  = $parentRefereree";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("上级推荐人增加注册好友数失败:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,'','addFail',$cid,"上级推荐人增加注册好友数失败:".$ProductOrderModel->getLastSql());
                    return;
                }
            }
            if ($uid != $saleSource && $saleSource){
                $res = self::checkSaleSource($saleSource,$cid);
                if($res){
                    $data['uid'] = $saleSource;
                    $data['cid'] = $cid;
                    $saleSource_statistics->add($data);
                }
                $query = "UPDATE wx_salesource_statistics SET miUCount = miUCount + 1 WHERE cid = $cid AND uid  = $saleSource";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("上级推荐人增加注册好友数失败:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,'','addFail',$cid,"上级推荐人增加注册好友数失败:".$ProductOrderModel->getLastSql());
                    return;
                }
            }
            if ($qId){
                $query = "UPDATE wx_miyouquan SET miUCount = miUCount + 1 WHERE id = $qId";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("营销圈增加注册好友数失败:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,'','addFail',$cid,"营销圈增加注册好友数失败:".$ProductOrderModel->getLastSql());
                    return;
                }
            }
        }
        if(($uid != $miUid || empty($uid)) && $miUid){
            $res = self::checkMiU($miUid,$cid);
            if($res){
                $data['uid'] = $miUid;
                $data['cid'] = $cid;
                $miu_statistics->add($data);
            }
            $query = "UPDATE wx_miu_statistics SET friendCount = friendCount + 1 WHERE cid = $cid AND uid  = $miUid";
            $result = $ProductOrderModel->query($query);
            if ($result === false) {
                Log::write("注册好友增加普通好友数失败:".$ProductOrderModel->getLastSql());
                $ProductOrderModel->rollback();
                self::statisStatus($module,$moduleId,'','addFail',$cid,"注册好友增加注册好友数失败:".$ProductOrderModel->getLastSql());
                return;
            }
        }
        if ($referrrUid && $uid){
            $res = self::checkMiU($referrrUid,$cid);
            if($res){
                $data['uid'] = $referrrUid;
                $data['cid'] = $cid;
                $miu_statistics->add($data);
            }
            $query = "UPDATE wx_miu_statistics SET friendCount = friendCount + 1 WHERE cid = $cid AND uid  = $referrrUid";
            $result = $ProductOrderModel->query($query);
            if ($result === false) {
                Log::write("推荐人增加普通好友数失败:".$ProductOrderModel->getLastSql());
                $ProductOrderModel->rollback();
                self::statisStatus($module,$moduleId,'','addFail',$cid,"推荐人增加注册好友数失败:".$ProductOrderModel->getLastSql());
                return;
            }
        }
        if ($parentRefereree){
            $res = self::checkMiU($parentRefereree,$cid);
            if($res){
                $data['uid'] = $parentRefereree;
                $data['cid'] = $cid;
                $miu_statistics->add($data);
            }
            $query = "UPDATE wx_miu_statistics SET friendCount = friendCount + 1 WHERE cid = $cid AND uid  = $parentRefereree";
            $result = $ProductOrderModel->query($query);
            if ($result === false) {
                Log::write("上级推荐人增加普通好友数失败:".$ProductOrderModel->getLastSql());
                $ProductOrderModel->rollback();
                self::statisStatus($module,$moduleId,'','addFail',$cid,"上级推荐人增加注册好友数失败:".$ProductOrderModel->getLastSql());
                return;
            }
        }
        if ($uid != $saleSource && $saleSource){
            $res = self::checkSaleSource($saleSource,$cid);
            if($res){
                $data['uid'] = $saleSource;
                $data['cid'] = $cid;
                $saleSource_statistics->add($data);
            }
            $query = "UPDATE wx_salesource_statistics SET friendCount = friendCount + 1 WHERE cid = $cid AND uid  = $saleSource";
            $result = $ProductOrderModel->query($query);
            if ($result === false) {
                Log::write("上级推荐人增加普通好友数失败:".$ProductOrderModel->getLastSql());
                $ProductOrderModel->rollback();
                self::statisStatus($module,$moduleId,'','addFail',$cid,"上级推荐人增加注册好友数失败:".$ProductOrderModel->getLastSql());
                return;
            }
        }
        $ProductOrderModel->commit();
        self::statisStatus($module,$moduleId,'','addSuccess',$cid);

    }

    /**
     * 删除注册好友/普通好友数量
     * @param $mimaId           mimall_user主键id
     * @param $customerId       cid
     */
    public function reduceFriendsNumber($mimaId, $customerId){
        Session::switchCustomer(0);
        $miMallUserModel = M("mimall_user");
        $quanUserModel = M("quan_user");
        $miu_statistics = M('miu_statistics');
        $saleSource_statistics = M('salesource_statistics');
        $ProductOrderModel = M();
        Session::switchCustomer($customerId);
        $miUserInfo = $miMallUserModel->where(['id' => $mimaId])->find();
        $module = 'mimall';
        $moduleId = $mimaId;
        $uid = $miUserInfo['uId'];
        $miUid = $miUserInfo['miUid'];
        $referrrUid = $miUserInfo['refereeUid'];
        $parentRefereree = $miUserInfo['preRefereeUid'];
        $saleSource = $miUserInfo['saleSource'];
        $cid = $miUserInfo['cId'];
        $qId = $miUserInfo['qId'];
        $isMiu = $quanUserModel->where(['uid' => $uid, 'qid' => $qId, 'deleted' => 0, 'status' => 1])->count();
        $ProductOrderModel->startTrans();
        if($isMiu){
            if(($uid != $miUid || empty($uid)) && $miUid){
                $res = self::checkMiU($miUid,$cid);
                if($res){
                    $data['uid'] = $miUid;
                    $data['cid'] = $cid;
                    $miu_statistics->add($data);
                }
                $query = "UPDATE wx_miu_statistics SET miUCount = miUCount - 1 WHERE cid = $cid AND uid  = $miUid";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("注册好友减少注册好友数失败:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,'','deleteFail',$cid,"注册好友减少注册好友数失败:".$ProductOrderModel->getLastSql());
                    return;
                }
            }
            if ($referrrUid){
                $res = self::checkMiU($referrrUid,$cid);
                if($res){
                    $data['uid'] = $referrrUid;
                    $data['cid'] = $cid;
                    $miu_statistics->add($data);
                }
                $query = "UPDATE wx_miu_statistics SET miUCount = miUCount - 1 WHERE cid = $cid AND uid  = $referrrUid";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("推荐人减少注册好友数失败:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,'','deleteFail',$cid,"推荐人减少注册好友数失败:".$ProductOrderModel->getLastSql());
                    return;
                }
            }
            if ($parentRefereree){
                $res = self::checkMiU($parentRefereree,$cid);
                if($res){
                    $data['uid'] = $parentRefereree;
                    $data['cid'] = $cid;
                    $miu_statistics->add($data);
                }
                $query = "UPDATE wx_miu_statistics SET miUCount = miUCount - 1 WHERE cid = $cid AND uid  = $parentRefereree";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("上级推荐人减少注册好友数失败:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,'','deleteFail',$cid,"上级推荐人减少注册好友数失败:".$ProductOrderModel->getLastSql());
                    return;
                }
            }
            if ($uid != $saleSource && $saleSource){
                $res = self::checkSaleSource($saleSource,$cid);
                if($res){
                    $data['uid'] = $saleSource;
                    $data['cid'] = $cid;
                    $saleSource_statistics->add($data);
                }
                $query = "UPDATE wx_salesource_statistics SET miUCount = miUCount - 1 WHERE cid = $cid AND uid  = $saleSource";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("上级推荐人减少注册好友数失败:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,'','deleteFail',$cid,"上级推荐人减少注册好友数失败:".$ProductOrderModel->getLastSql());
                    return;
                }
            }
            if ($qId){
                $query = "UPDATE wx_miyouquan SET miUCount = miUCount - 1 WHERE id = $qId";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("营销圈减少注册好友数失败:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,'','deleteFail',$cid,"营销圈减少注册好友数失败:".$ProductOrderModel->getLastSql());
                    return;
                }
            }
        }
        if(($uid != $miUid || empty($uid)) && $miUid){
            $res = self::checkMiU($miUid,$cid);
            if($res){
                $data['uid'] = $miUid;
                $data['cid'] = $cid;
                $miu_statistics->add($data);
            }
            $query = "UPDATE wx_miu_statistics SET friendCount = friendCount - 1 WHERE cid = $cid AND uid  = $miUid";
            $result = $ProductOrderModel->query($query);
            if ($result === false) {
                Log::write("注册好友减少普通好友数失败:".$ProductOrderModel->getLastSql());
                $ProductOrderModel->rollback();
                self::statisStatus($module,$moduleId,'','deleteFail',$cid,"注册好友减少注册好友数失败:".$ProductOrderModel->getLastSql());
                return;
            }
        }
        if ($referrrUid){
            $res = self::checkMiU($referrrUid,$cid);
            if($res){
                $data['uid'] = $referrrUid;
                $data['cid'] = $cid;
                $miu_statistics->add($data);
            }
            $query = "UPDATE wx_miu_statistics SET friendCount = friendCount - 1 WHERE cid = $cid AND uid  = $referrrUid";
            $result = $ProductOrderModel->query($query);
            if ($result === false) {
                Log::write("推荐人减少普通好友数失败:".$ProductOrderModel->getLastSql());
                $ProductOrderModel->rollback();
                self::statisStatus($module,$moduleId,'','deleteFail',$cid,"推荐人减少注册好友数失败:".$ProductOrderModel->getLastSql());
                return;
            }
        }
        if ($parentRefereree){
            $res = self::checkMiU($parentRefereree,$cid);
            if($res){
                $data['uid'] = $parentRefereree;
                $data['cid'] = $cid;
                $miu_statistics->add($data);
            }
            $query = "UPDATE wx_miu_statistics SET friendCount = friendCount - 1 WHERE cid = $cid AND uid  = $parentRefereree";
            $result = $ProductOrderModel->query($query);
            if ($result === false) {
                Log::write("上级推荐人减少普通好友数失败:".$ProductOrderModel->getLastSql());
                $ProductOrderModel->rollback();
                self::statisStatus($module,$moduleId,'','deleteFail',$cid,"上级推荐人减少注册好友数失败:".$ProductOrderModel->getLastSql());
                return;
            }
        }
        if ($uid != $saleSource && $saleSource){
            $res = self::checkSaleSource($saleSource,$cid);
            if($res){
                $data['uid'] = $saleSource;
                $data['cid'] = $cid;
                $saleSource_statistics->add($data);
            }
            $query = "UPDATE wx_salesource_statistics SET friendCount = friendCount - 1 WHERE cid = $cid AND uid  = $saleSource";
            $result = $ProductOrderModel->query($query);
            if ($result === false) {
                Log::write("上级推荐人减少普通好友数失败:".$ProductOrderModel->getLastSql());
                $ProductOrderModel->rollback();
                self::statisStatus($module,$moduleId,'','deleteFail',$cid,"上级推荐人减少注册好友数失败:".$ProductOrderModel->getLastSql());
                return;
            }
        }
        $ProductOrderModel->commit();
        self::statisStatus($module,$moduleId,'','deletedSuccess',$cid);

    }

    /**
     * 分享次数人数统计
     */
    public function shareStatis(){
        Session::switchCustomer(0);
        $redis = new RedisAPI();
        $max = $redis->lLen("shareStatis");
        $arr = $redis->LRANGE("shareStatis", 0, -1);
        $count = 0;
        while ($count < $max) {
            $count++;
            $param = $redis->lPop("shareStatis");
            if(empty($param)){
                continue;
            }
            $params = json_decode($param, true);
            $this->addViewCount($params);
            $this->updateViewCount($params);
        }
    }
    //记录用户对商品的巨鹿添加pv统计，uv统计
    public function addViewCount($param){
        $customerId = Session::$user['customerId'];
        $uid = $param['uid'];
        $sId=$param['sId'];
        $miUId=$param['miUId'];
        $qId=$param['qId'];
        Session::switchCustomer(0);
        $uStaModel=M("mishare_stat");
        $uVisiModel=M("mishare_visit");
        Session::switchCustomer($customerId);
        $result=$uStaModel->where("sId='$sId' and miUid='$miUId'")->find();
        if(!$result) {
            $data=array(
                "sId"=>$sId,
                "miUid"=>$miUId,
                "shareCount"=>0,
                "praiseCount"=>0,
                "quanId"=>$qId,
                "uv"=>0,
                "pv"=>0,
                "createTime"=>date("Y-m-d H:i:s")
            );
            $id=$success=$uStaModel->add($data);
        } else {
            $id=$result["id"];
        }
        $uStaModel->where("id='$id'")->setInc('pv');//pv+1
        //判断是否更新uv
        $visitResult=$uVisiModel->where("uId=$uid and sId=$sId")->find();
        if(!$visitResult) {
            $uStaModel->where("id='$id'")->setInc('uv');//uv+1
            $staResult=$uStaModel->where("id='$id'")->find();
            if($staResult) {
                //触发uv任务
                $p=new StdClass();
                $p->miUId=$param['miUId'];
                $p->qId=$qId;
                Log::write("开始调用任务更新");
                Module::callModule("task", Session::$user,"updateTaskStatus", $p);
            }
        }
        return $success;
    }
    /**
     * [updateViewCount 更新浏览数]
     * @param  [type] $param [description]
     * @return [type]        [description]
     */
    public function updateViewCount($param){
        $sId=$param['sId'];
        $uid = $param['uid'];
        $lastShareUid=$param['lastShareUId'];
        $visitId=$param['visitId'];
        $customerId = $param['cid'];
        $qid = $param['qId'];
        Session::switchCustomer(0);
        $sModel=M("mishare");
        $sFromModel=M("mishare_from");
        $uVisiModel=M("mishare_visit");

        Session::switchCustomer($customerId);
        $sModel->where('id=' .$sId)->setInc('viewCount');
        if($uid==$lastShareUid){
            return;
        }

        $moduleInfo = $sModel->where('id=' .$sId)->field('module,moduleId')->find();
        $module = $moduleInfo['module'];
        $moduleId = $moduleInfo['moduleId'];
        $where = ['module' => $module];
        $where['moduleId'] = ['eq', $moduleId];
        $result = $uVisiModel->where($where)->group('cid,uId')->field('id')->select();
        $result = count($result);
        $sModel->where('id=' .$sId)->setField('viewUv',$result);


        if(!empty($visitId) && !empty($lastShareUid)){
            $fromInfo = $sFromModel->where(['visitId' => $visitId, 'uid' => $lastShareUid])->find();
            $id = $fromInfo['id'];
            $saleSourceUid = $fromInfo['saleSourceUid'];
            $sFromModel->where(['visitId' => $visitId, 'id' => $id])->setInc('viewCount');	//---给分享人加浏览次数

            self::addUserStatis($lastShareUid,$customerId);             //---给普通用户加分享浏览次数
            self::addMiuStatis($lastShareUid,$customerId);              //---给注册好友加分享浏览次数
            self::addSaleSourceStatis($saleSourceUid,$customerId);      //---给销售员加分享浏览次数
            self::addMiYouQuanStatis($qid);      //---给销售员加分享浏览次数



            $count = $uVisiModel->where(['visitId' => $visitId, 'uId' => $uid])->count(); //查看
            if($count == 1){
                $sFromModel->where(['visitId' => $visitId, 'id' => $id])->setInc('viewUv');//---给分享人加浏览人数
                $field = 'shareUv';
                self::addUserStatis($lastShareUid,$customerId,$field);      //---给普通用户加分享浏览人数
                self::addMiuStatis($lastShareUid,$customerId,$field);       //---给注册好友加分享浏览人数
                self::addSaleSourceStatis($saleSourceUid,$customerId,$field);//---给销售员加分享浏览人数
        }
        }
    }
    //---给普通用户加分享浏览人数/次数
    public  function addUserStatis($uid,$cid,$field='sharePv'){
        Session::switchCustomer(0);
        $user_statistics = M('user_statistics');
        Session::switchCustomer($cid);
        $result = self::checkUser($uid,$cid);
        if($result){
            $data['uid'] = $uid;
            $data['cid'] = $cid;
            $user_statistics->add($data);
        }
        $user_statistics->where(['uid' => $uid, 'cid' => $cid])->setInc($field);

    }
    //---给注册好友加分享浏览人数/次数
    public function addSaleSourceStatis($uid,$cid,$field='sharePv'){
        Session::switchCustomer(0);
        $salesource_statistics = M('salesource_statistics');
        Session::switchCustomer($cid);
        $result = self::checkSaleSource($uid,$cid);
        if($result){
            $data['uid'] = $uid;
            $data['cid'] = $cid;
            $salesource_statistics->add($data);
        }
        /** 5.添加普通用户浏览次数*/
        $salesource_statistics->where(['uid' => $uid, 'cid' => $cid])->setInc($field);
    }
    //---给销售员加分享浏览人数/次数
    public function addMiuStatis($uid,$cid,$field='sharePv'){
        Session::switchCustomer(0);
        $miu_statistics = M('miu_statistics');
        $quan_user = M('quan_user');
        Session::switchCustomer($cid);
        $where['b.cId'] = array('eq', $cid);
        $where['a.uId'] = array('eq', $uid);
        $where['a.deleted'] = array('eq', 0);
        $userInfo = $quan_user->alias('a')->where($where)->join('wx_miyouquan as b on a.qid=b.id')->field('qid')->find();
        if(!empty($userInfo['qid'])){
            $resuft = $this->checkMiU($uid,$cid);
            if($resuft){
                $data['uid'] = $uid;
                $data['cid'] = $cid;
                $miu_statistics->add($data);
            }
            /** 5.添加密友分享总次数*/
            $miu_statistics->where(['uid' => $uid, 'cid' => $cid])->setInc($field);
        }
    }
    //---给营销圈加分享浏览人数
    public function addMiYouQuanStatis($qid,$cid){
        Session::switchCustomer(0);
        $miyouquan = M('miyouquan');
        Session::switchCustomer($cid);
        $miyouquan->where(['id' => $qid])->setInc('shareUv');
    }













}